What are compound operators in JavaScript?
Below is a list of compound operators in JavaScript:
-
+=is compound addition operator. -
-=is compound subtraction operator. -
*=is compound multiplication operator. -
/=is compound division operator. -
%=is compound modulo operator. -
**=is compound exponential operator.
Compound addition operator
This operator adds the right-side operand with the left-side operand and assigns the result to the left operand.
Syntax
x += y
Example
let x = 10;x += 5;console.log(x);
Explanation
Line 1: We declare the variable x and store 10 in it.
Line 2: We add 5 to x and then assign the result to the x.
Line 3: We print the value of x.
Compound subtraction operator
This operator subtracts the right-side operand from the left-side operand and then assigns the result to the left operand.
Syntax
x -= y
Example
let x = 10;x -= 5;console.log(x);
Explanation
Line 1: We declare the variable x and store 10 into it.
Line 2: We subtract 5 from x and assign the result to x.
Line 3: We print the value of x.
Compound multiplication operator
This operator multiplies the right-side operand with left side operand and then assigns the result to the left operand.
Syntax
x *= y
Example
let x = 10;x *= 5;console.log(x);
Explanation
Line 1: We declare the variable x and store 10 into it.
Line 2: We multiply 5 with x and then assign the result to the x.
Line 3: We print the value of x.
Compound division operator
This operator divides the left operand with the right operand and then assigns it to the left operand.
Syntax
x /= y
Example
let x = 10;x /= 5;console.log(x);
Explanation
Line 1: We declare the variable x and store 10 into it.
Line 2: We divide x with 5 and then assign the result to the x.
Line 3: We print the value of x.
Compound modulo operator
This operator takes modulo after dividing the left operand with the right operand and then assigns the result to the left operand.
Syntax
x %= y
Example
let x = 10;x %= 5;console.log(x);
Explanation
Line 1: We declare the variable x and store 10 into it.
Line 2: We divide x with 5 and take modulo and then assign the result to the x.
Line 3: We print the value of x.
Compound exponential operator
This operator calculates the exponent (raised power) value using operands and then assigns the value to the left operand.
Syntax
x **= y
Example
let x = 10;x **= 5;console.log(x);
Explanation
Line 1: We declare the variable x and store 10 into it.
Line 2: We multiply the value of x with the value of x five times and then store the result to x.
Line 3: We print the value of x.
Free Resources