Number Coercion in JavaScript
In JavaScript, coercion refers to the automatic or implicit conversion of values from one data type to another. When different types of operators are applied to values, JavaScript performs type coercion to ensure that the operation can proceed. Let’s explore some common examples of coercion:
1. Undefined to NaN:
When you perform an operation involving undefined, JavaScript returns NaN (Not-a-Number).
const result = undefined + 10;
console.log(result); // NaN
Output
NaN
2. Null to 0:
The value null is coerced to 0 when used in arithmetic operations.
const total = null + 5;
console.log(total); // 5
Output
5
3. Boolean to Number:
Boolean values (true and false) are converted to numbers: 1 for true and 0 for false.
const num1 = true + 10;
const num2 = false + 10;
console.log(num1);
console.log(num2);
Output
11 10
4. String to Number
When performing arithmetic operations, JavaScript converts strings to numbers. If the string cannot be parsed as a valid number, it returns NaN.
const str1 = '42';
const str2 = 'hello';
const numFromString1 = Number(str1);
const numFromString2 = Number(str2);
console.log(numFromString1);
console.log(numFromString2);
Output
42 NaN
5. BigInts and Symbols
Attempting to coerce Symbol values to numbers results in a TypeError.
const symbolValue = Symbol('mySymbol');
const numFromSymbol = Number(symbolValue); // TypeError
console.log(numFromSymbol);
Output:
TypeError: Cannot convert a Symbol value to a number
Integer conversion
Some operations such as those which work with an array, string indexes, or date/time expect integers. After performing the coercion if the number is greater than 0 it is returned as the same and if the number NaN or -0, it is returned as 0. The result is always an integer.
Fixed-width number Conversion
In Javascript, there are some functions that deal with the binary encoding of integers such as bitwise operators and typedArray objects. The bitwise operators always convert the operands to 32-bit integers.
JavaScript Numbers
JavaScript Numbers are primitive data types. Unlike other programming languages, you don’t need int, float, etc. to declare different numeric values. JavaScript numbers are always stored in double-precision 64-bit binary format IEEE 754.
This format stores numbers in 64 bits,
- 0-51 bit stores value(fraction)
- 52-62 bit stores exponent
- 63-bit stores sign