[JavaScript] How to change other types to number efficiently (Unary plus)?

·

1 min read

[JavaScript] How to change other types to number efficiently (Unary plus)?

People often think of Number() or parseInt() method when they convert different types into a number.

const id = "3";
console.log(typeof id)
// string

console.log(Number(id));
// 3
console.log(parseInt(id, 10));
// 3

But there is a more simple and efficient way to change different types into a number. The unary plus (+) operator precedes its operand and evaluates to its operand but attempts to convert it into a number, if it isn't already. Unary plus is the fastest and preferred way of converting something into a number, because it does not perform any other operations on the number.

Unary plus does the same steps as normal number coercion used by most built-in methods expecting numbers. It can convert string representations of integers and floats, as well as the non-string values true, false, and null. Integers in both decimal and hexadecimal (0x-prefixed) formats are supported. Negative numbers are supported (though not for hex). If it cannot parse a particular value, it will evaluate to NaN. Unlike other arithmetic operators, which work with both numbers and BigInts, using the + operator on BigInt values throws a TypeError.

const x = 1;
const y = -1;

console.log(+x);
// 1

console.log(+y);
// -1

console.log(+'');
// 0

console.log(+true);
// 1

console.log(+false);
// 0

console.log(+'hello');
// NaN

console.log(+1n);
// TypeError: Cannot convert BigInt value to number