JavaScript Compound Assignment With Augmented Subtraction

Posted by

In JavaScript, the compound assignment with augmented subtraction operator is written as -=. It is used to subtract a value from a variable and assign the result to the variable. Here is an example of how it can be used:

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

let x = 10;
x -= 5;
console.log(x); // Output: 5

[/dm_code_snippet]

In the example above, the value of x is first set to 10. Then, the compound assignment with augmented subtraction operator is used to subtract 5 from x and assign the result (5) back to x. Finally, the value of x is logged to the console and it is output as 5.

You can also use the compound assignment with augmented subtraction operator to subtract a variable from another variable, like this:

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

let x = 10;
let y = 5;
x -= y;
console.log(x); // Output: 5

[/dm_code_snippet]

In this example, the value of x is first set to 10 and the value of y is set to 5. Then, the compound assignment with augmented subtraction operator is used to subtract the value of y from x and assign the result (5) back to x. Finally, the value of x is logged to the console and it is output as 5.

Here are a few more examples of how the compound assignment with augmented subtraction operator can be used in JavaScript:

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

let x = 10;
x -= 3;
console.log(x); // Output: 7

let y = 20;
y -= 5;
console.log(y); // Output: 15

let z = 100;
z -= z;
console.log(z); // Output: 0

[/dm_code_snippet]

In the first example, the value of x is set to 10 and then 3 is subtracted from it using the compound assignment with augmented subtraction operator. The result (7) is then assigned back to x and logged to the console.

In the second example, the value of y is set to 20 and then 5 is subtracted from it using the compound assignment with augmented subtraction operator. The result (15) is then assigned back to y and logged to the console.

In the third example, the value of z is set to 100 and then z is subtracted from itself using the compound assignment with augmented subtraction operator. The result (0) is then assigned back to z and logged to the console.