JavaScript ToNumber Operation Tutorial

In this section, we will learn what the ToNumber operation is and how does it works in JavaScript.

What is ToNumber Operation in JavaScript?

When there’s a non-Number type value involved in an operation that needs values of type Number, the execution engine will run the `ToNumber` operation on the target value to coerce that value into Number data type.

Example: ToNumber operation in JavaScript

const res = "20" * 10;

console.log(res);

Output:

200

Take a look at this statement:

const res = "20" * 10;

Here the first operand is the String value `20`. But because here we have the multiplication operation, both operands should be of type Number.

So the execution engine will run the `ToNumber` operation on the first operand and coerce that value into number type.

Note: if the result of this coercion is a non-numeric value, then the execution engine will return the value `NaN` instead. We will explain the value `NaN` in later sections, but in short this value stands for `Not a Number` and refers to the fact that the target value that the execution engine tried to coerce didn’t result a value of type Number.

Example: JavaScript ToNumber operation and the NaN value

const res = "sdfds" * 10;

console.log(res);

Output:

NaN

The result of multiplying the value `NaN` to another value is again `NaN`. That’s how we got this value on the console.

List of Primitive Values and the Result of Applying ToNumber Operation

In the table below you can see a list of primitive values and the result of applying `ToNumber` operation on them:

Primitive value After ToNumbr operation
“” 0
“0” 0
“-0” -0
“009” 9
“3.14159” 3.14159
“0.” 0
“.0” 0
“sfsdf” NaN
“0xaf” 175
false 0
true 1
null 0
undefined NaN

Example: converting Boolean to number in JavaScript

console.log(20 - true);

Output:

19

Example: converting string to number in JavaScript

console.log("18" - true);

Output:

17

JavaScript Object to Number

Applying the `ToNumber` operation to values of type object (including arrays) will cause the `valueOf()` method of that target object to be invoked. Or, to be more specific, the execution engine will run the `ToPrimitive` operation on that object. The details are explained in the ToPrimitive section.

There are a few corner cases to be aware of when invoking the `ToNumber` operation on objects, as the table below shows:

Object value After ToNumber operation
[“”] 0
[“0”] 0
[“-0”] -0
[null] 0
[undefined] 0
[1,2,3] NaN
[[[[]]]] 0
{/*body…*/} NaN
{valueOf(){return 10;}} 10

Example: converting object to number in JavaScript

const obj = {
  name: "John", 
  age: 200,
  valueOf(){
    return this.age; 
  }
}
console.log(obj - 50);

Output:

150
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies