Documenting Problems That Were Difficult To Find The Answer To

Node.JS String Length Undefined

This issue arose using node.js version v0.10.3.

Here’s some example code:

function writeStringLength( str ) {
  console.log( "str = \"" + str + "\"" );
  console.log( "str.length is " + str.length );

  var copy = str;
  console.log( "copy.length is " + copy.length );

  var copyObj = new String( str );
  console.log( "copyObj.length is " + copyObj.length );

var now = new Date();
writeStringLength( now.getFullYear() );

This outputs:

user@localhost:/tmp$ /usr/local/node/bin/node /tmp/brokenstring.js
str = "2013"
str.length is undefined
copy.length is undefined
copyObj.length is 4

So – why does JavaScript think the string doesn’t have a defined value for the length property? According to the Node.JS manual entry for the String object “JavaScript distinguishes between String objects and primitive string values”. Conversion of primitive strings to String objects should happen automatically but clearly in this case node.js is unable to determine that the function parameter is a string that needs “boxing” into a string object. By forcing a new String object to be created we can be sure the length property will return a useful value.

Note that the values returned by the Date() object functions causes this problem – perhaps because Node.JS doesn’t know for certain what kind of values these functions returns (could they be from an external library?). Whereas if you try and pass an ordinary string (e.g. “example”) to writeStringLength() then the parameter will, as expected, have a defined length property. Perhaps this is because node.js knows the parameter is an explicitly defined string in this example.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: