Arithmetic Operations

JavaScript FAQ | JavaScript Numbers FAQ  

Question: What arithmetic operations are supported in JavaScript?

Answer: JavaScript supports the following arithmetic operations (which you can group in brackets to form more complex expressions):

Unary operations have one operand (in the following examples, the operand is

-a   // change the sign of a
~a   // bitwise NOT a
++a  // add 1 to a (before using a)
a++  // add 1 to a (after using a)
--a  // subtract 1 from a (before using a)
a--  // subtract 1 from a (after using a)

Binary operations have two operands (in these examples, the operands are

a * b    // multiply a by b
a / b    // divide a by b
a % b    // find the remainder of division of a by b
a + b    // add a and b
a - b    // subtract b from a
a & b    // bitwise a AND b
a | b    // bitwise a OR b
a ^ b    // bitwise a XOR b

Caution! If at least one of the values

is a string rather than a number, then the operation  
a + b
  is treated as a string concatenation, and not as an arithmetic addition.

Shifts are the following operations:

a << b   // shift a by b bits to the left
         // (padding with zeros)
a >> b   // shift a by b bits to the right
         // (copying the sign bit)
a >>> b  // shift a by b bits to the right 
         // (padding with zeros)

When using arithmetic operations, it is important to remember that internally JavaScript stores numbers as floating-point values according to the IEEE-754 Standard. Integers less than 253 by absolute value are always represented exactly, while bigger integers might or might not be represented exactly; e.g. odd integers greater than 253 lose one or more of their least significant digits. (See Accuracy for more information on this.)

To complicate matters even further, JavaScript performs bitwise operators and shifts as if the operands were 32-bit integers:
(1) the operand is temporarily converted to a 32-bit integer value,
(2) the bitwise operation or shift is performed on the 32-bit value,
(3) the result is converted back to the IEEE-754 floating point format.

This means that in JavaScript shift and bitwise operators may be noticeably slower than in other languages such as C or C++. (Note also that performance of JavaScript arithmetic will strongly depend on the user's browser – and, in particular, whether the browser uses a JIT compiler or an interpreter for JavaScript code.)

See also:

Copyright © 1996-2018,