JavaScript Assignment Operators
Assignment operators in JavaScript are used to assign values to variables.
They can also update the value of a variable by combining an operation with assignment.
1. Basic Assignment (=
)
Assigns a value to a variable.
let x = 10; // x now holds 10
2. Add and Assign (+=
)
Adds a value to the variable and updates it.
let x = 5;
x += 3; // Same as x = x + 3
console.log(x); // 8
3. Subtract and Assign (=
)
Subtracts a value from the variable and updates it.
let x = 10;
x -= 4; // Same as x = x - 4
console.log(x); // 6
4. Multiply and Assign (=
)
Multiplies the variable by a value and updates it.
let x = 5;
x *= 2; // Same as x = x * 2
console.log(x); // 10
5. Divide and Assign (/=
)
Divides the variable by a value and updates it.
let x = 20;
x /= 4; // Same as x = x / 4
console.log(x); // 5
6. Modulus and Assign (%=
)
Calculates remainder and updates the variable.
let x = 10;
x %= 3; // Same as x = x % 3
console.log(x); // 1
Summary Table
Operator | Meaning | Example |
---|---|---|
= | Assign | x = 5 |
+= | Add & assign | x += 3 |
-= | Subtract & assign | x -= 2 |
*= | Multiply & assign | x *= 2 |
/= | Divide & assign | x /= 4 |
%= | Modulus & assign | x %= 3 |