Type Conversion
In JavaScript, values may be of different types. Changing the type of a variable can be done by explicit type conversion. Besides that, JavaScript also performs type coercion (implicit type conversion) when the context requires it.
Type Conversion
JavaScript does not have a construct to cast into a (different) type like many other languages but some built-in helpers can be used instead. Most notably, Boolean, Number and String can be used as functions to convert a value to the respective type.
Converting to a Boolean (Truthy/Falsy Values)
With Boolean(value) you can convert any value to a boolean. There is a fixed set of values, so called falsy values, that convert to false. Most importantly, false, 0, empty string, null, undefined and NaN are falsy.
For all other values, Boolean returns true. These values are called truthy.
Boolean(-1);
// => true
Boolean(0);
// => false
Boolean(' ');
// => true
Boolean('');
// => false
Note that because of the described rules, '0', 'false', [] and {} are truthy in JavaScript.
Converting to a Number
Number(value) can be used to convert a value to a number. Whitespaces at the beginning and the end of a string are ignored and an empty string is converted to 0. If you try to convert a non-primitive value or a string that does not represent a number, the result is NaN (Not-A-Number).
Number(' -12.34 ');
// => -12.34
Number('1,2');
// => NaN
Number('');
// => 0
Number({ num: 123 });
// => NaN
Converting to a String
With String(value) you can convert a value to a string. The result is what you would expect it to be for primitive values.
String(12.34);
// => '12.34'
String(false);
// => 'false'
String(null);
// => 'null'
String(undefined);
// => 'undefined'
For arrays, the String function will apply the string conversion for each element and join the results with a comma. You can also apply the join method yourself, e.g. to customize the separator. Note that in these cases null and undefined will be converted to an empty string.
String([42, null, true, 'abc']);
// => '42,,true,abc'
For objects, by default String returns an unhelpful text.
String({ key: 'value' });
// => '[object Object]'
Learn More
- https://javascript.info/type-conversions
- https://javascript.info/object-toprimitive
- https://www.freecodecamp.org/news/js-type-coercion-explained-27ba3d9a2839/
References:
Backlinks