Mathematical Assignment Operators

 VARIABLES

Let’s consider how we can use variables and math operators to calculate new values and assign them to a variable. Check out the example below:

let w4;
ww1;

console.log(w); // Output: 5

In the example above, we created the variable w with the number 4 assigned to it. The following line, w = w + 1, increases the value of w from 4 to 5.

Another way we could have reassigned w after performing some mathematical operation on it is to use built-in mathematical assignment operators. We could re-write the code above to be:

let w4;
w += 1;

console.log(w); // Output: 5

In the second example, we used the += assignment operator to reassign w. We’re performing the mathematical operation of the first operator + using the number to the right, then reassigning w to the computed value.

We also have access to other mathematical assignment operators: -=*=, and /= which work in a similar fashion.

let x20;
x -= 5; // Can be written as x = x - 5
console.log(x); // Output: 15

let y50;
y *= 2; // Can be written as y = y * 2
console.log(y); // Output: 100

let z8;
z /= 2; // Can be written as z = z / 2
console.log(z); // Output: 4

Let’s practice using these mathematical assignment operators!


Instructions:

1.Use the += mathematical assignment operator to increase the value stored in levelUp by 5.


2.Use the -= mathematical assignment operator to decrease the value stored in powerLevel by 100.


3.Use the *= mathematical assignment operator to multiply the value stored in multiplyMe by 11.


4.Use the /= mathematical assignment operator to divide the value stored in quarterMe by 4.


Solution:

let levelUp = 10;
levelUp+= 5; // 10+5 = 15
let powerLevel = 9001;
powerLevel-= 100; // 9001-100 = 8901
let multiplyMe = 32;
multiplyMe*=11; //32*11 = 352
let quarterMe = 1152;
quarterMe/=4; // 1152/4 = 288

// Use the mathematical assignments in the space below:






// These console.log() statements below will help you check the values of the variables.
// You do not need to edit these statements.
console.log('The value of levelUp:', levelUp);
console.log('The value of powerLevel:', powerLevel);
console.log('The value of multiplyMe:', multiplyMe);
console.log('The value of quarterMe:', quarterMe);


In the console:

The value of levelUp: 15
The value of powerLevel: 8901
The value of multiplyMe: 352
The value of quarterMe: 288

Comments

Popular posts from this blog

String Interpolation(*** Template Literals***)