3.3 The Assignment Operators
The second category of operators is the assignment family. You've already used the simple assignment operator = to store a value in a variable, for example x = 10. JavaScript also offers compound assignment operators that combine assignment with arithmetic. They are shortcuts that read the current value of a variable, transform it, and assign the new value back in a single statement.
From increment to compound assignment
The increment operator x++ seen in the previous lesson is equivalent to x = x + 1. But what if you want to add 5 instead of 1? The increment operator won't help. The compound operator += does:
x = x + 5; // explicit form
x += 5; // shortcut — exactly equivalent
The same logic applies to multiplication: x = x * 3 can be written x *= 3. Every arithmetic operator has its compound assignment variant:
+=— add then assign-=— subtract then assign*=— multiply then assign/=— divide then assign%=— remainder then assign**=— exponentiate then assign
Compound operators keep code concise and intent-revealing. In the next video, we'll move on to comparison operators.
Summary
Assignment operators in JavaScript allow you to assign and modify variable values. The simple assignment operator (=) assigns a value directly, while compound assignment operators (+=, -=, *=, /=) combine arithmetic operations with assignment, enabling concise value modifications. These operators reduce code verbosity and improve readability by providing shortcuts for common operations.
Key points
- The simple assignment operator (=) assigns a value to a variable (e.g., x = 10)
- Compound assignment operators combine arithmetic with assignment (+=, -=, *=, /=, etc.)
- x += 5 is equivalent to x = x + 5; this pattern applies to all arithmetic operators
- The increment operator (++) adds 1 to a variable, equivalent to x += 1
- All arithmetic operators (addition, subtraction, multiplication, division) can be combined with assignment
FAQ
What is the difference between the = and += operators?
The = operator directly assigns a value (x = 10). The += operator adds a value to the current value and assigns the result (x += 5 means x = x + 5).
Can I use any arithmetic operator with assignment?
Yes. You can use +=, -=, *=, /=, and other arithmetic operators combined with the assignment operator to perform operations and assignment in one step.
What does the increment operator (++) do?
The increment operator (++) adds 1 to a variable. x++ is equivalent to x = x + 1 and provides a shorthand for incrementing by one.