JavaScript Assignment Operator
By Flavio Copes
Learn how the JavaScript assignment operator = sets a value on a variable, and the compound shortcuts +=, -=, *=, /= and %= that combine it with arithmetic.
Use the assignment operator = to assign a value to a variable:
const a = 2
let b = 2
var c = 2
The left side is the variable, the right side is the value. Once assigned, the variable name gives you back that value anywhere in scope.
Note that with const the assignment can only happen once, at declaration time. With let and var you can reassign later:
let score = 0
score = 10
The compound assignment operators
This operator has several shortcuts for all the arithmetic operators which let you assign to the first operand the result of the operations with the second operand.
They are:
+=: addition assignment-=: subtraction assignment*=: multiplication assignment/=: division assignment%=: remainder assignment**=: exponentiation assignment
Examples:
let a = 0
a += 5 //a === 5
a -= 2 //a === 3
a *= 2 //a === 6
a /= 2 //a === 3
a %= 2 //a === 1
To be clear, the above operations are executed one after another, so
aat the end is 1, not 0
Each one is just a shorter way to write the full expression. a += 5 means exactly a = a + 5.
They exist because “take this variable, change it, put it back” is one of the most common things we do in code. Counters, running totals, accumulating strings: all shorter with compound assignment.
Speaking of strings, += works on them too, because + concatenates:
let greeting = 'Hello'
greeting += ' Flavio'
//greeting === 'Hello Flavio'
Be careful with types here. If you add a number to a string, the number gets converted to a string:
let label = 'test'
label += 5
//label === 'test5', not an error
A classic pitfall: = inside a condition
Assignment is an expression, so it produces a value: the value you assigned. That means this code is valid JavaScript, but it’s almost never what you want:
let logged = false
if (logged = true) {
//this ALWAYS runs, and logged is now true
}
One = assigns. The condition evaluates to true because that’s the assigned value, and the variable gets overwritten too.
The fix is using the comparison operator, ===:
if (logged === true) {
//runs only when logged is true
}
If you use a linter, this mistake gets flagged automatically. One more reason to have one running.
Related posts about js: