Skip to content

Assignment operators in JavaScript | Basics

  • by

The javaScript assignment operators (=) is used to assign a value to a variable. The Simple syntax of the assignment operator is as follows:

x = y

Assigns a value to a variable.

let x = 10; 

The += assignment operator adds a value to a variable.

let x = 10;
x += 5; 

Assignment operators in JavaScript

Simple example code.

<!DOCTYPE html>
<html>
<body>
  <script>
    let x = 2;
    const y = 3;

    console.log(x);
    console.log(x = y + 1); // 3 + 1
    console.log(x = x * y); // 4 * 3
    console.log(x -= 5) // 12 - 5

  </script>
</body>
</html>

Output:

Assignment operators in JavaScript

The following table illustrates assignment operators that are shorthand for another operator and the assignment:

OperatorMeaningDescription
a = ba = bAssigns the value of b to a.
a += ba = a + bAssigns the result of a plus b to a.
a -= ba = a - bAssigns the result of a minus b to a.
a *= ba = a * bAssigns the result of a times b to a.
a /= ba = a / bAssigns the result of a divided by b to a.
a %= ba = a % bAssigns the result of a modulo b to a.
a &=ba = a & bAssigns the result of a AND b to a.
a |=ba = a | bAssigns the result of a OR b to a.
a ^=ba = a ^ bAssigns the result of a XOR b to a.
a <<= ba = a << bAssigns the result of a shifted left by b to a.
a >>= ba = a >> bAssigns the result of a shifted right (sign preserved) by b to a.
a >>>= ba = a >>> bAssigns the result of a shifted right by b to a.

JavaScript Chaining assignment operators

If you want to assign a single value to multiple variables, you can chain the assignment operators. For example:

let a = 10, b = 20, c = 30;
a = b = c; // all variables are 30

Do comment if you have any doubts or suggestions on this Js operator topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading