1. Home
  2. >
  3. Type conversions in javascript explained
2

Type conversions in javascript explained
rahoolbenji

String Conversion – Occurs when we output something. Can be performed with String(value).

Numeric Conversion – Occurs in math operations. Can be performed with Number(value).

The conversion follows the rules:

ValueBecomes…
undefinedNaN
null0
true / false1 / 0
stringThe string is read “as is”, whitespaces from both sides are ignored. An empty string becomes 0. An error gives NaN.

Boolean Conversion 

Follows the rules:

ValueBecomes…
0, null, undefined, NaN, ""false
any other valuetrue

Most of these rules are easy to understand and memorize:

  • undefined is NaN as a number, not 0.
  • "0" and space-only strings like " " are true as a boolean.
console.log( "6" / "2" ); // 3, strings are converted to numbers




let str = "123";
console.log(typeof str); // string

let num = Number(str); // becomes a number 123

console.log(typeof num); // number




let age = Number("an arbitrary string instead of a number");

console.log(age); // NaN, conversion failed



console.log( Number("   123   ") ); // 123
console.log( Number("123z") );      // NaN (error reading a number at "z")
console.log( Number(true) );        // 1
console.log( Number(false) );       // 0




console.log( Boolean(1) ); // true
console.log( Boolean(0) ); // false

console.log( Boolean("hello") ); // true
console.log( Boolean("") ); // false



console.log( Boolean("0") ); // true
console.log( Boolean(" ") ); 


# javascript