JavaScript Type Conversion

JavaScript variables can be converted from one data type to another, either automatically (implicit coercion) or manually (explicit conversion). Understanding type conversion is crucial for avoiding bugs and writing predictable code.

Converting to String

The String() function explicitly converts any value to a string. String(123) returns "123", String(true) returns "true", String(null) returns "null". This function works with all data types and always produces a string representation. It's the most reliable way to convert values to strings.

The toString() method is available on most values (except null and undefined) and converts them to strings. (123).toString() returns "123", true.toString() returns "true". toString() is slightly less universal than String() because calling it on null or undefined throws an error, but it's commonly used and supported on numbers, booleans, arrays, and objects.

Concatenating any value with an empty string (value + "") implicitly converts the value to a string. This is a common shorthand: 123 + "" gives "123". JavaScript's type coercion automatically converts the number to a string when you use + with a string. This trick is concise but can be less readable than explicit String().

Implicit string conversion happens automatically when you use the + operator with a string and another value. JavaScript prioritizes string concatenation, so 5 + "3" becomes "53" (not 8). The non-string value is converted to a string and concatenated. This automatic conversion can cause subtle bugs if you're not careful about types.

All JavaScript values have a string representation. Even complex objects can be converted to strings, though the default representation may not be useful ("{} [object Object]"). Arrays convert to comma-separated values. Functions convert to their source code. Understanding these conversions helps when debugging or displaying values.

// String() function
console.log(String(123));    // "123"
console.log(String(true));   // "true"
console.log(String(null));   // "null"

// toString() method
let num = 123;
console.log(num.toString()); // "123"

// Implicit conversion
console.log(123 + "");       // "123"
console.log(true + "");      // "true"

// Template literals
let value = 42;
console.log(`Value: ${value}`); // "Value: 42"

Converting to Number

The Number() function converts values to numbers. Number("123") returns 123, Number("12.34") returns 12.34, Number(true) returns 1, Number(false) returns 0. Number() is strict—if it can't convert the entire value, it returns NaN. Number("123px") returns NaN because of the non-numeric characters.

The parseInt() function parses a string and returns an integer, discarding any decimal portion. parseInt("123.45") returns 123. It reads from the beginning and stops at the first non-numeric character: parseInt("123px") returns 123. Always provide a radix (base) as the second argument: parseInt("08", 10) to avoid unexpected octal interpretations.

The parseFloat() function parses a string and returns a floating-point number, preserving decimals. parseFloat("123.45") returns 123.45. Like parseInt(), it stops at the first invalid character: parseFloat("123.45abc") returns 123.45. parseFloat() only parses base-10 numbers, unlike parseInt() which accepts different bases.

The unary + operator is a quick shorthand to convert values to numbers: +"123" returns 123, +true returns 1. It works the same as Number() but is more concise. Developers commonly use +value as a one-character type conversion. However, Number() is more explicit and readable for those unfamiliar with the + trick.

Type conversion to number follows specific rules: empty string "" converts to 0, string with spaces " " converts to 0, strings with non-numeric characters convert to NaN, true converts to 1, false to 0, null to 0, undefined to NaN. These rules can cause unexpected results—be careful with implicit conversions.

// Number() function
console.log(Number("123"));    // 123
console.log(Number("12.34"));  // 12.34
console.log(Number(""));       // 0
console.log(Number("Hello"));  // NaN
console.log(Number(true));     // 1
console.log(Number(false));    // 0

// parseInt and parseFloat
console.log(parseInt("123"));    // 123
console.log(parseInt("123.45")); // 123
console.log(parseFloat("123.45")); // 123.45

// Unary + operator
console.log(+"123");  // 123
console.log(+true);   // 1

Converting to Boolean

The Boolean() function explicitly converts any value to a boolean (true or false). Boolean(1) returns true, Boolean(0) returns false, Boolean("hello") returns true, Boolean("") returns false. Every JavaScript value has an inherent truthiness or falsiness that Boolean() makes explicit.

There are exactly six falsy values in JavaScript—values that convert to false: the boolean false itself, the number 0 (and -0), the empty string "", null, undefined, and NaN. These six values, and only these, convert to false when converted to boolean. Everything else is truthy.

All other values besides the six falsy values are truthy and convert to true. This includes all non-zero numbers (even negative numbers), all non-empty strings (even "false" and "0"), all objects, all arrays (even empty ones), and all functions. Understanding what's truthy vs falsy is essential for writing correct conditional logic.

A common source of confusion: empty arrays [] and empty objects {} are truthy, not falsy. They convert to true even though they're "empty." This is because they're objects, and all objects are truthy. To check if an array is empty, check its length property: if (array.length). To check if an object is empty, use Object.keys(obj).length.

Boolean conversion happens automatically in conditional contexts like if statements, while loops, ternary operators, and logical operations. You don't need to call Boolean() explicitly in these contexts—JavaScript does it automatically. However, the double NOT operator (!!) is commonly used as shorthand for Boolean(): !!value converts value to its boolean equivalent.

// Boolean() function
console.log(Boolean(1));        // true
console.log(Boolean(0));        // false
console.log(Boolean("Hello"));  // true
console.log(Boolean(""));       // false
console.log(Boolean(null));     // false
console.log(Boolean(undefined)); // false
console.log(Boolean(NaN));      // false

// Truthy values
console.log(Boolean([]));       // true (empty array)
console.log(Boolean({}));       // true (empty object)
console.log(Boolean("0"));      // true (string)

// Double NOT operator
console.log(!!"Hello"); // true
console.log(!!0);       // false