In JavaScript, the assignment operator “=” is used to assign a value to a variable. This operator provides shortcuts for performing arithmetic operations and assigning the result to the variable.
Let’s look at some examples:
const a = 2;
let b = 2;
var c = 2;
In the above code, the assignment operator is used to assign the value 2 to the variables a
, b
, and c
.
The assignment operator also has shortcuts for arithmetic operations. Here are some common shortcuts:
+=
: addition assignment-=
: subtraction assignment*=
: multiplication assignment/=
: division assignment%=
: remainder assignment**=
: exponentiation assignment
These shortcuts allow you to perform an arithmetic operation and assign the result to the variable in a single step.
Let’s see them in action:
let a = 0;
a += 5; // a is now 5
a -= 2; // a is now 3
a *= 2; // a is now 6
a /= 2; // a is now 3
a %= 2; // a is now 1
In the above code, the value of a
is modified using the corresponding shortcut assignment operators. The final value of a
is 1, not 0, because the operations are executed one after another.
In conclusion, the assignment operator in JavaScript provides a convenient way to assign values to variables and perform arithmetic operations at the same time. By utilizing the shortcuts, you can simplify your code and make it more concise.