JS Fundamentals - Type Conversions Flashcards
Type Conversion
Most of the time, operators and functions automatically convert the values given to them to the right type.
For example, alert automatically converts any value to a string to show it. Mathematical operations convert values to numbers.
There are also cases when we need to explicitly convert a value to the expected type.
String conversion
We can also call the String(value) function to convert a value to a string:
Example of String Conversion
let value = true; alert(typeof value); // boolean
value = String(value); // now value is a string “true”
alert(typeof value); // string
String conversion is mostly obvious. A false becomes “false”, null becomes “null”, etc.
Numeric Conversion
alert( "6" / "2" ); // 3, strings are converted to numbers let str = "123"; alert(typeof str); // string
let num = Number(str); // becomes a number 123
alert(typeof num); // number
When does NaN happen in Numeric conversion
let age = Number(“an arbitrary string instead of a number”);
alert(age); // NaN, conversion failed
Examples of Numeric Conversion
Value Becomes… undefined NaN null 0 true and false 1 and 0 string Whitespaces from the start and end are removed. If the remaining string is empty, the result is 0. Otherwise, the number is “read” from the string. An error gives NaN.
null and undefined
Please note that null and undefined behave differently here: null becomes zero while undefined becomes NaN.
Boolean Conversion
It happens in logical operations (later we’ll meet condition tests and other similar things) but can also be performed explicitly with a call to Boolean(value).
The conversion rule:
Values that are intuitively “empty”, like 0, an empty string, null, undefined, and NaN, become false.
Other values become true.
Please Note
Some languages (namely PHP) treat “0” as false. But in JavaScript, a non-empty string is always true.
alert( Boolean(“0”) ); // true
alert( Boolean(“ “) ); // spaces, also true (any non-empty string is true)