Chuyển đến nội dung

Bài 17 · Operators

Arithmetic and Assignment Operators

Do math in JavaScript with + - * / % and **, understand precedence, increment and decrement, compound assignment like +=, and joining strings with +.

An operator is a symbol that takes one or more values and produces a new one. You've already used several: + to add, = to store a value in a variable, === to compare. This chapter looks at the operators one family at a time, starting with the ones you'll use most: arithmetic operators for math and assignment operators for storing and updating values.

Most of them work exactly as they did in school, but a few have details worth knowing — what % does with negative numbers, why x++ and ++x differ, and how + switches between adding and joining text.

The arithmetic operators

JavaScript has six arithmetic operators that work on two values:

Operator Meaning Example Result
+ addition 7 + 2 9
- subtraction 7 - 2 5
* multiplication 7 * 2 14
/ division 7 / 2 3.5
% remainder 7 % 2 1
** exponent (power) 7 ** 2 49
JS Arithmetic basics

Press Run (or Ctrl + Enter) to see the console output here.

No output.

There's no separate integer division in JavaScript: / always gives the exact (floating-point) quotient. To get a whole number, round the result with a method from The Math Object, such as Math.floor() or Math.trunc().

Dividing by zero doesn't crash, either. 5 / 0 is Infinity, -5 / 0 is -Infinity, and 0 / 0 is NaN. Any arithmetic involving NaN produces NaN — see Numbers for how to detect it.

The remainder operator %

a % b gives what's left over after dividing a by b as many whole times as possible. It's much more useful than it first looks:

JS Using the remainder

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Checking for even numbers, doing something every nth time, wrapping around a cycle and splitting seconds into minutes are the four patterns you'll use again and again.

Negative numbers: in JavaScript, the result of % takes the sign of the left operand: -7 % 3 is -1, not 2. That's why % is called the remainder operator rather than modulo. To always get a non-negative result for a positive n, use ((a % n) + n) % n.

Precedence: which operator goes first

When an expression mixes operators, JavaScript follows precedence rules, like the order of operations in math:

  1. ( ) — parentheses first
  2. ** — exponent
  3. *, /, % — left to right
  4. +, - — left to right

So 2 + 3 * 4 is 14, not 20. The exponent is special: it groups from the right, so 2 ** 3 ** 2 means 2 ** (3 ** 2), which is 512.

JavaScript
2 + 3 * 4;        // 14
(2 + 3) * 4;      // 20
10 - 4 - 3;       // 3   (left to right: (10 - 4) - 3)
2 ** 3 ** 2;      // 512 (right to left)

You don't need to memorize a full precedence table. If an expression makes you stop and think, add parentheses — they cost nothing and make the intent obvious to every reader.

One quirk: JavaScript refuses to guess what -2 ** 2 means, and reports a SyntaxError. Write (-2) ** 2 (which is 4) or -(2 ** 2) (which is -4).

Unary plus and minus

Some operators take a single value. Unary minus flips the sign: -x. Unary plus converts its operand to a number: +"42" is 42. Both apply the conversion rules from Type Conversion and Coercion:

JavaScript
const input = "15";
-input;   // -15
+input;   // 15
+"";      // 0
+"abc";   // NaN

Increment and decrement

Adding or subtracting one is so common that it has its own operators: ++ adds 1 to a variable and -- subtracts 1. They change the variable itself, so they need a let (not const):

JS Prefix vs postfix

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The position matters only when you use the result in the same expression:

  • Postfix x++ returns the value before the change.
  • Prefix ++x returns the value after the change.

On a line of its own, as in lives--; or the update part of a for loop (i++), both forms do the same thing. Many developers avoid using ++ inside larger expressions, because total = count++ * 2 makes the reader stop and think. Write count += 1 on its own line when in doubt.

Assignment and compound assignment

The plain assignment operator = stores the value on the right in the variable on the left. It isn't "equals" in the math sense — x = x + 1 is perfectly valid and means "take the current value, add one, store the result".

Because "update a variable based on its current value" is so common, every arithmetic operator has a compound assignment shortcut:

Shortcut Same as
x += 5 x = x + 5
x -= 5 x = x - 5
x *= 5 x = x * 5
x /= 5 x = x / 5
x %= 5 x = x % 5
x **= 5 x = x ** 5
JS Updating values in place

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The bitwise operators have compound forms too: x &= m, x |= m, x ^= m, x <<= n, x >>= n and x >>>= n. The |= form is handy for switching flags on:

JavaScript
const READ = 1, WRITE = 2;
let permissions = 0;
permissions |= READ;   // 1
permissions |= WRITE;  // 3: both flags set
console.log(permissions);

See Bitwise Operators for how these work bit by bit.

There are also logical assignment operators — ||=, &&= and ??= — covered in Logical Operators and Short-Circuiting.

+ with strings

As you saw in Type Conversion and Coercion, + does double duty. With two numbers it adds; if either side is a string, it concatenates (joins) instead:

JS Concatenation pitfalls

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Because + evaluates left to right, once a string appears every later + joins text. Wrap math in parentheses, convert input to numbers first, or — best of all — build text with template literals.

Check your understanding

Quick check · 5 questions

of 5 answered You scored / 5 · perfect!

  1. 1. What is 2 + 3 * 2 ** 2?

    ** first (2 ** 2 = 4), then * (3 × 4 = 12), then + (2 + 12 = 14).
  2. 2. What does 17 % 5 evaluate to?

    5 fits into 17 three times (15), leaving a remainder of 2.
  3. 3. After let n = 4; const m = n++;, what are n and m?

    Postfix ++ returns the old value (4) and then increments n to 5.
  4. 4. What does "Score: " + 3 + 2 produce?

    Left to right: the string is joined with 3, then with 2. Use parentheses or a template literal to add first.
  5. 5. Which line is equivalent to price = price * 0.9?

    *= multiplies the variable by the right side and stores the result back.

Summary

  • Arithmetic operators: +, -, *, / (always exact division), % (remainder, sign follows the left side) and ** (power).
  • Precedence: parentheses, then ** (right to left), then * / %, then + -. Add parentheses whenever it helps.
  • ++ and -- change a variable by one; postfix returns the old value, prefix the new one.
  • Compound assignment (+=, -=, *=, /=, %=, **=) updates a variable in place.
  • + joins text as soon as a string is involved — convert input first or use template literals.

Next: Comparison and Equality — comparing values with ===, <, > and Object.is.

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.