How Can We Help?

# Assignment Operators

## Introduction to JavaScript assignment operators

An assignment operator (`=`) assigns a value to a variable. The syntax of the assignment operator is as follows:

``````let a = b;
``````

In this syntax, JavaScript evaluates the expression `b` first and assigns the result to the variable `a`.

The following example declares the `counter` variable and initializes its value to zero:

``````let counter = 0;
``````

The following example increases the `counter` variable by one and assigns the result to the `counter` variable:

``````let counter = 0;
counter = counter + 1;
``````

When evaluating the second statement, JavaScript evaluates the expression on the right-hand first (`counter + 1`) and assigns the result to the `counter` variable. After the second assignment, the `counter` variable is `1`.

To make the code more concise, you can use the `+=` operator like this:

``````let counter = 0;
counter += 1;
``````

In this syntax, you don’t have to repeat the `counter` variable twice in the assignment.

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

Operator Meaning Description
a = b a = b Assigns the value of b to a.
a += b a = a + b Assigns the result of a plus b to a.
a -= b a = a – b Assigns the result of a minus b to a.
a *= b a = a * b Assigns the result of a times b to a.
a /= b a = a / b Assigns the result of a divided by b to a.
a %= b a = a % b Assigns the result of a modulo b to a.
a &=b a = a & b Assigns the result of a AND b to a.
a =b a = a
a ^=b a = a ^ b Assigns the result of a XOR b to a.
a <<= b a = a << b Assigns the result of a shifted left by b to a.
a >>= b a = a >> b Assigns the result of a shifted right (sign preserved) by b to a.
a >>>= b a = a >>> b Assigns the result of a shifted right by b to a.

## Chaining JavaScript 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
``````

In this example, JavaScript evaluates from right to left. Therefore, it does the following:

``````let a = 10, b = 20, c = 30;

b = c;// b is 30
a = b;// a is also 30
``````

## Summary

• Use the assignment operator (`=`) to assign a value to a variable.
• Chain the assignment operators if you want to assign a single value to multiple variables.