This process is known as type conversion.
String() function. For example, the following code converts the boolean value false to a string:
1const bool = false;2const str = String(bool); // "false"
Boolean() function which follows two simple rules:
- Values that are intuitively “empty”, like 0, an empty string, null, undefined, and NaN, become
- Other values become
1const str = "hello";2const bool = Boolean(str); // true3const zero = 0;4const zeroToBool = Boolean(zero) // false
Number() function. For example, the following code converts the integer 2 to a floating-point number:
1const num = 2;2const float = Number(num); // 2.0
In addition to converting between integer and floating-point numbers, the
Number() function can also be used to convert other types of values to numbers. For example, it can be used to convert a string representation of a number to an actual number value.
1const str = "3.14";2const num = Number(str); // 3.14
It's important to note that, in some cases, the
Number() function may not be able to perform a numeric conversion. For example, if the input value is a non-numeric string or an array, the function will return the special value NaN (Not a Number).
1const str = "hello";2const num = Number(str); // NaN