javascript:   'String(value)'   vs.  'value.toString'  What's the difference ?

sidwelle
sidwelle used Ask the Experts™
on
javascript:   'String(value)'   vs.  'value.toString()'  What's the difference ?

I searched and found a post on 'stackOverflow' that states the only difference is that 'String(value)' is the equivalent of calling 'String("" + value)'  and this causes it to handle null values correctly.

Doing my own testing I found that:
   myStr = String(value);    myType = typeof(myStr);   // 'myType' returns a string value of 'string'
   myLen = myStr.length;     // have to use 'length'  w/o following parentheses or w/parens it throws an error:  TypeError: Cannot call property length in object myValue It is not a function, it is "number"

Open in new window

but, it works if the object string is empty/null ?

Where:
 
 myStr = value.toString();   myType = typeof(myStr);  // 'myType' returns a string value of 'object'
   myLen = myStr.length();    // have to use 'length()' followed w/parentheses or function definition is returned:  "function length() {/* int length()  */}"

Open in new window

But throws an error if the object is empty/null: TypeError: Cannot call property length in object . It is not a function, it is "number".

Is there a foolproof way to get the length w/o testing for variable type and having multiple scenarios ?
Thanks
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Software Engineer
Top Expert 2011
Commented:
Basically the first is returning a primitive string and the second is a String object.

Primitive types don't have methods hence why you can't call .length() which is a method call on an string object.

I'm not completely sure what you are asking for when you ask for a foolproof method, if you create your strings using String(value) then you need to use .length to get the length of the string, if you use value.ToString() then you have to use .length().
It is up to you how the string is created in the code, is it not?

Author

Commented:
This is what I need to know.  I get a value returned by an object that I don't always have control of, so I was looking for one method that would return the length no matter what's the type.

Thank you

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial