Type Conversion

by jeremyjones on March 20, 2011

  • Share
  • CevherShare
  • Share

JavaScript has member functions for all objects, such as valueof and toString. When you use literal numbers, Booleans, strings, undefined and null are different from the counterparts that you use for objects. This example shows this:

<br />
Typeof new Number(i);	// Returns object<br />
Typeof I;		// Returns number<br />

There are ways that you can implicitly convert an object into a literal number, boolean or string. You can convert any object into a number if you add it to zero like this:

<br />
Myval + 0;<br />

If you want to convert an object to a string, just add it to a null string like in this example:

<br />
Myval + ‘’;<br />

When you add a string and a number, the result will depend on the values of the string. If the string is empty, it will force it to the number zero. If the string is not empty, the zero will convert to a string and string concatenation occurs.

<br />
0 + '' == 0<br />
'' + 0 == 0<br />
1 + '' == 1<br />
'' + 1 == 1<br />
0 + 'a' == '0a'<br />
'a' + 0 == 'a0'<br />

If you want to convert an object into a boolean value, simply negate it twice. This will convert the object into true or false:

<br />
!!Myval;<br />

These are great ways to convert types in JavaScript. Knowing how these work could really help to improve your code.

Leave a Comment

Previous post:

Next post: