Arithmetic Operators

Having explained operator precedence, associativity, and other background material, we can start to discuss the operators themselves. This section details the arithmetic operators:

Addition (+)

The + operator adds numeric operands or concatenates string operands. If one operand is a string, the other is converted to a string and the two strings are then concatenated. Object operands are converted to numbers or strings that can be added or concatenated. The conversion is performed by the valueOf( ) method and/or the toString( ) method of the object.

Subtraction (-)

When - is used as a binary operator, it subtracts its second operand from its first operand. If used with non-numeric operands, it attempts to convert them to numbers.

Multiplication (*)

The * operator multiplies its two operands. If used with non-numeric operands, it attempts to convert them to numbers.

Division (/)

The / operator divides its first operand by its second. If used with non-numeric operands, it attempts to convert them to numbers. If you are used to programming languages that distinguish between integer and floating-point numbers, you might expect to get an integer result when you divide one integer by another. In JavaScript, however, all numbers are floating-point, so all divisions have floating-point results: 5/2 evaluates to 2.5, not 2. Division by zero yields positive or negative infinity, while 0/0 evaluates to NaN.

Modulo (%)

The % operator computes ...

Get JavaScript: The Definitive Guide, Fourth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.