Arithmetic Operators
In JavaScript, you have the usual arithmetic operators:
1 + 2; // add
9 / 3; // divide
1 * 5; // multiply
9 - 5; // subtract
10 % 4; // modulus (division remainder)
-
The
/operator yields a floating-point result.console.log(9 / 3); // 3 console.log(1 / 2); // 0.5 -
The
%operator works with both integer and non-integer numbers.console.log(42 % 10); // 2 console.log(1.1 % 0.3); // 0.20000000000000012 -
The
**operator is the exponentiation operator (similar to Python): it raises a number to a power.console.log(2 ** 10); // 1024 console.log(2 ** 0.5); // 1.4142135623730951 -
If an operand is
NaN, so is the result.console.log(2 + NaN); // NaN
Combined assignment operators
Similar to Java, C++ and many other programming languages, you have combined assignment operators:
let counter = 1;
counter += 10;
console.log(counter); // 11
console.log((counter -= 2)); // 9
Increment and decrement operators
Similar to Java, C++ and many other programming languages, you have increment and decrement operators:
let counter = 1;
console.log(counter++); // 1
console.log(counter); // 2
console.log(++counter); // 3
console.log(--counter); // 2
Type conversions
Type coercion is another term for type conversion. It is the term the JavaScript community uses more often.
Let’s see what happens when we mix types in arithmetic operations.
console.log("3" - 2); // ?
The output is 1. The non-number operand is converted to a number.
Now, what about this?
console.log("3" + 2); // ?
The output is 32. Why? Here, the + operator concatenates strings: the non-string operand is converted to a string.