 JavaScript Arithmetic Operators

Most arithmetical operators in JavaScript - including addition, subtraction, division and multiplication - work just as you might expect. However, there are several edge cases that can make for some confusing exceptions, and several additional operators that you may not be familiar with.

Works exactly as you might expect. In the console:

1 + 1
> 2
var a = 2, b = 4;
a + b;
> 6

However, there are some oddities. Adding strings creates concatenation:

"Bill" + "Oddy";
> BillOddy

…while adding Boolean values creates numerical results that correspond to Boolean states:

var a = true, b = false;
a + b;
> 1
var a = false, b = 0;
a + b;
> 0

Increment: ++

Adds 1 to the current number; frequently used in loops.

var i = 12;
i++;
> 13

Subtraction: -

Performs just like the mathematical operator, including the production of negative numbers:

var x = 22, y = 42;
x - y;
> -20

Decrement: --

Subtracts 1 from the current number. Again, often used in loops.

var m = 22;
m--;
> 21

Division: /

Division works as expected:

var numerator = 2, divisor = 3;
numerator / divisor;
> 0.666666

Division by 0 is a problem, obviously:

2 / 0
> Infinity

Multiplication: *

Also works as expected; note that the operator is the asterisk symbol, not x.

var bird = 2, hand = 3, bush = 4;
bird * hard * bush;
> 24

Modulus: %

Divides two values and provides the remainder. Frequently used with time, date and calendar operations.

6 % 4
> 2

(Meaning: 6 can be divided by 4 once, leaving 2 left over)

There’s a known, long-standing bug in JavaScript that leaves modulo arithmetic incorrect in some cases: a modulo operation should never result in a negative, but dividing a negative number by a positive one will do just that:

-5 % 4
> -1

Order of Operations

In JavaScript, multiplication and division happen before addition and subtraction; order of execution doesn’t depend on the order of operators in this case. This can lead to poorly-written expressions creating unexpected results:

2 + 4 * 5
> 22

To make the order clear, place terms in parentheses: these will be executed first:

(2 + 4) * 5
> 30

Photograph by Hernán Piñera, used under a Attribution-ShareAlike Creative Commons license

Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.