Mathematical Assignment Operator - 03

We can use variables and math operators to calculate a new value and assign them to a new variable. Let’s look at the following example…

let x = 4;
x = x + 1; 

Here, we have declared a variable named x with the number 4 assigned to it. On the following line, the value increases from 4 to 5.

Notice attentively that we have used the x variable on the left and right side of the assignment operators (=). The variable x is used here twice, which is redundant and confusing. This is also a problem. 


We can solve this problem. JavaScript has some built-in mathematical assignment operators that make it easy to calculate a new value and assign it to the same variable without writing the variable twice.


let x = 4;
x +=2;       // x equals to 6;

let y = 4;
y -= 2;      // y equals to 2;

let z = 4;
z *= 2;     // z equals to 8;

let r = 4;
r++;       //  r equals to 5;

let  t = 4;
t--;     //  t equals to 3;
The above three examples are used to calculate a new variable and assign these to the same variable. And the last two examples are used for the increment and decrement of the value of the variable.

Post a Comment

Previous Post Next Post