Operators in JavaScript Revealed - Subtraction (Part 2)

by:

Share:  

A quick tour on how subtraction operators work in the JavaScript Language (Part 2)



Operators in JavaScript (Part 2)

Continuing from our discussion on operators, it's now time to talk about the subtraction operator.

Subtraction Operator

The Substraction operator - applies primarily to numbers. In JavaScript, it's essential to understand how this operator works as many programming languages have different behaviour.

In this first example, we will look into how to subtract two whole integers:

var first = 20;
var second = 10;
var sum = first - second;
console.log(total); // 10

When two floating point numbers are subtracted from each other, JavaScript is less predictable as we start noticing rounding errors.

var first = 4.2;
var second = 2.8;
var sum = first - second;
console.log(total); // 1.4000000000000004

One way to solve this is to make use of the Number.toFixed() method. The argument to the toFixed method dictates the decimal precision of the number.

var first = 4.2;
var second = 2.8;
var sum = first - second;
console.log(total.toFixed(1)); // 1.4

If we take two string values, and subtract one from the other, an implicit numeric conversion occurs:

var first = "240";
var second = "80";
var sum = first - second;
console.log(total); // 160

If the values of a string contains characters other than numbers, the result evaluates to a NaN or Not a Number.

var first = "AA240";
var second = "BB80";
var sum = first - second;
console.log(total); // NaN

If one of the values is undefined, the result evaluates to NaN:

var first = "200";
var second = undefined;
var sum = first - second;
console.log(total); // NaN

If one of the values is null, the null object evaluates to 0:

var first = "200";
var second = null;
var sum = first - second; // 200 - 0
console.log(total); // 200

If one of the values is a NaN, the result evaluates to a NaN:

var first = "200";
var second = NaN;
var sum = first - second;
console.log(total); // NaN

If one of the values is an empty string, the empty string evalates to a 0:

var first = "200";
var second = "";
var sum = first - second;
console.log(total); // 200

We can also make set of the valueOf property of an object and then perform numeric calculations on that object:

var first = 500;
var second = {
    valueOf: function() { return 100; }
};

var sum = first - second;
console.log(sum); // 400

Do you use the subtraction operator in JavaScript or want to suggest an improvement to this article? Please share it with us by leaving a reply below.

Stay tuned for Part 3 where we will talk about the multiplication operator.


About the Author

Alvin Luchmun
Alvin Luchmun is a freelance developer, trainer and co-founder at and currently lives in London. Alvin is passionate about anything tech/biz related but is also a firm believer in agile clean code, he loves preaching about code to fellow humanoids!.

Leave a comment