The compound assignment operator with augmented multiplication (*=) is an operator that combines the multiplication and assignment operators. It takes the form of x *= y
, and is equivalent to x = x * y
.
This operator can be used to multiply a variable by a value and assign the result to the same variable, all in a single statement.
For example:
[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 = 5; x *= 2; console.log(x); // Output: 10
[/dm_code_snippet]
Here, the variable x
is initialized with the value 5
, and then multiplied by 2
using the compound assignment operator. The result of 5 * 2
is 10
, which is then assigned back to x
. The final value of x
is 10
.
The compound assignment with augmented multiplication operator can be used with any data type that can be multiplied, including numbers and strings.
For example:
[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 str = "Hello"; str *= 3; console.log(str); // Output: "HelloHelloHello"
[/dm_code_snippet]
Here, the string "Hello"
is multiplied by 3
, which results in a new string that is the concatenation of three copies of the original string. The final value of str
is "HelloHelloHello"
.
It’s important to note that the compound assignment with augmented multiplication operator does not support the multiplication of a string and a number. If you try to use it in this way, you will get a NaN
(Not a Number) result.
Here are a few more examples of using the compound assignment with augmented multiplication operator:
[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 a = 2; let b = 3; a *= b; console.log(a); // Output: 6 b *= a; console.log(b); // Output: 18 let c = "5"; c *= 2; console.log(c); // Output: 10 let d = "Hello"; d *= 3; console.log(d); // Output: "HelloHelloHello" let e = "5"; e *= "2"; console.log(e); // Output: NaN
[/dm_code_snippet]
In the first example, the variables a
and b
are both multiplied using the compound assignment operator, and the results are assigned back to the same variables.
In the second example, the string "5"
is multiplied by 2
, which results in a number (10
).
In the third example, the string "Hello"
is multiplied by 3
, which results in a new string that is the concatenation of three copies of the original string.
In the fourth example, the string "5"
is multiplied by the string "2"
, which is not a valid operation and results in NaN
.
I hope these examples help clarify how the compound assignment with augmented multiplication operator works. Let me know if you have any more questions!