Assignment operators assign values to JavaScript variables.
Operator | Example | Same As |
---|---|---|
= | x = y | x = y |
+= | x += y | x = x + y |
-= | x -= y | x = x – y |
*= | x *= y | x = x * y |
/= | x /= y | x = x / y |
%= | x %= y | x = x % y |
<<= | x <<= y | x = x << y |
>>= | x >>= y | x = x >> y |
>>>= | x >>>= y | x = x >>> y |
&= | x &= y | x = x & y |
^= | x ^= y | x = x ^ y |
|= | x |= y | x = x | y |
**= | x **= y | x = x ** y |
The **=
operator is a part of ECMAScript 2016.
Assignment Examples
The =
assignment operator assigns a value to a variable.
Assignment
<!DOCTYPE html> <html> <body> <h2>JavaScript Assignments</h2> <h3>The = Operator</h3> <p id="demo"></p> <script> let x = 10; document.getElementById("demo").innerHTML = x; </script> </body> </html>
Result:
JavaScript Assignments
The = Operator
10
The +=
assignment operator adds a value to a variable.
Assignment
<!DOCTYPE html> <html> <body> <h2>JavaScript Assignments</h2> <h3>The += Operator</h3> <p id="demo"></p> <script> let x = 10; x += 5; document.getElementById("demo").innerHTML = x; </script> </body> </html>
Result:
JavaScript Assignments
The += Operator
15
The -=
assignment operator subtracts a value from a variable.
Assignment
<!DOCTYPE html> <html> <body> <h2>JavaScript Assignments</h2> <h3>The -= Operator</h3> <p id="demo"></p> <script> let x = 10; x -= 5; document.getElementById("demo").innerHTML = x; </script> </body> </html>
Result:
JavaScript Assignments
The -= Operator
5
The *=
assignment operator multiplies a variable.
Assignment
<!DOCTYPE html> <html> <body> <h2>JavaScript Assignments</h2> <h3>The *= Operator</h3> <p id="demo"></p> <script> let x = 10; x *= 5; document.getElementById("demo").innerHTML = x; </script> </body> </html>
Result:
JavaScript Assignments
The *= Operator
50
The /=
assignment divides a variable.
Assignment
<!DOCTYPE html> <html> <body> <h2>JavaScript Assignments</h2> <h3>The /= Operator</h3> <p id="demo"></p> <script> let x = 10; x /= 5; document.getElementById("demo").innerHTML = x; </script> </body> </html>
Result:
JavaScript Assignments
The /= Operator
2
The %=
assignment operator assigns a remainder to a variable.
Assignment
<!DOCTYPE html> <html> <body> <h2>JavaScript Assignments</h2> <h3>The %= Operator</h3> <p id="demo"></p> <script> let x = 10; x %= 5; document.getElementById("demo").innerHTML = x; </script> </body> </html>
Result:
JavaScript Assignments
The %= Operator
0