Type Conversion in Javascript
Last Updated on: October 10, 2022
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:
Typeof new Number(i); // Returns object Typeof I;
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:
Myval + 0;
If you want to convert an object to a string, just add it to a null string, like in this example:
Myval + '';
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.
0 + '' == 0 '' + 0 == 0 1 + '' == 1 '' + 1 == 1 0 + 'a' == '0a' 'a' + 0 == 'a0'
If you want to convert an object into a boolean value, simply negate it twice. This will convert the object into true or false:
!!Myval;
These are great ways to convert types in JavaScript. Knowing how these work could help to improve your code.
Get notified of new posts: