JavaScript is a dynamically typed language, which means it often tries to automatically convert values from one data type to another. This process is called Type Coercion.
While automatic conversion can be convenient, it can also lead to unexpected bugs. To write robust code, it's important to understand both automatic (implicit) and manual (explicit) type conversion.
The easiest way to explicitly convert any value to a string is to use the global String() function.
console.log(String(123)); // "123" console.log(String(true)); // "true" console.log(String(null)); // "null" console.log(String(undefined)); // "undefined"
Alternatively, the toString() method can be used, but it will throw an error on null and undefined.
Implicit conversion to a string happens most often when using the + operator with a string.
let result = '5' + 5; // The number 5 is coerced to a string '5' console.log(result); // "55"
To explicitly convert a value to a number, use the global Number() function.
console.log(Number("3.14")); // 3.14
console.log(Number(" ")); // 0
console.log(Number("")); // 0
console.log(Number("99 88")); // NaN
console.log(Number("hello")); // NaN
console.log(Number(true)); // 1
console.log(Number(false)); // 0
console.log(Number(null)); // 0
console.log(Number(undefined)); // NaN
Implicit conversion to a number happens in mathematical expressions (except for + with a string).
console.log('6' / '2'); // 3
console.log('6' - 2); // 4
To explicitly convert a value to a boolean, use the global Boolean() function. The rules are simple: any value that is not "falsy" will convert to true.
There are only a handful of values in JavaScript that convert to false:
false0 (and -0)"" (empty string)nullundefinedNaNEverything else is "truthy" and converts to true! This includes empty arrays [] and empty objects {}.
// Falsy values
console.log(Boolean(0)); // false
console.log(Boolean("")); // false
console.log(Boolean(null)); // false
// Truthy values
console.log(Boolean(1)); // true
console.log(Boolean("hello")); // true
console.log(Boolean({})); // true
Implicit conversion to a boolean happens in logical contexts, like inside an if statement.
if ("hello") {
// This code runs because "hello" is truthy
console.log("This will be printed!");
}
Which of the following values is considered "truthy" in JavaScript and will convert to `true`?