To show variable type use typeof:
let value = true; console.log(typeof value); // boolean
Let’s convert our variable to string:
value = String(value); // now value is a string "true" console.log(typeof value); // string
Numeric Conversion
Numeric conversion happens in mathematical functions and expressions automatically.
For example, when division / is applied to non-numbers:
console.log( "6" / "2" ); // 3, strings are converted to numbers
We can use the Number(value) function to explicitly convert a value to a number:
let str = "123"; console.log(typeof str); // string let num = Number(str); // becomes a number 123 console.log(typeof num); // number
Explicit conversion is usually required when we read a value from a string-based source like a text form but expect a number to be entered.
If the string is not a valid number, the result of such a conversion is NaN
. For instance:
let age = Number("an arbitrary string instead of a number"); console.log(age); // NaN, conversion failed
Examples of numeric conversion:
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
Please note that null and undefined behave differently here: null becomes zero while undefined becomes NaN.
Boolean Conversion
The conversion rule:
Values that are intuitively “empty”, like 0, an empty string, null, undefined, and NaN, become false.
Other values become true.
For instance:
console.log( Boolean(1) ); // true console.log( Boolean(0) ); // false console.log( Boolean("hello") ); // true console.log( Boolean("") ); // false
Summary
The three most widely used type conversions are to string, to number, and to boolean.
String Conversion – Occurs when we output something. Can be performed with String(value)
. The conversion to string is usually obvious for primitive values.
Numeric Conversion– Occurs in math operations. Can be performed with Number(value)
.
Boolean Conversion – Occurs in logical operations. Can be performed with Boolean(value).