JavaScript Assignment operators
Assignment operators in JavaScript are used to assign values to variables. They not only assign values but can also perform arithmetic operations and assign the result back to the variable. Here's a breakdown of each type:
1. Basic Assignment (=
)
- Purpose: Assigns a value to a variable.
- Example:
let x = 10; // Assigns 10 to x
2. Addition Assignment (+=
)
- Purpose: Adds a value to a variable and assigns the result to that variable.
- Example:
let x = 10; x += 5; // Equivalent to x = x + 5; x is now 15
3. Subtraction Assignment (-=
)
- Purpose: Subtracts a value from a variable and assigns the result to that variable.
- Example:
let x = 10; x -= 3; // Equivalent to x = x - 3; x is now 7
4. Multiplication Assignment (*=
)
- Purpose: Multiplies a variable by a value and assigns the result to that variable.
- Example:
let x = 4; x *= 3; // Equivalent to x = x * 3; x is now 12
5. Division Assignment (/=
)
- Purpose: Divides a variable by a value and assigns the result to that variable.
- Example:
let x = 20; x /= 4; // Equivalent to x = x / 4; x is now 5
6. Modulus Assignment (%=
)
- Purpose: Applies the modulus operator to a variable and assigns the result to that variable.
- Example:
let x = 17; x %= 5; // Equivalent to x = x % 5; x is now 2
7. Exponentiation Assignment (**=
)
- Purpose: Raises a variable to the power of a value and assigns the result to that variable.
- Example:
let x = 2; x **= 3; // Equivalent to x = x ** 3; x is now 8
Key Points:
- Chaining: Assignment operators can be chained. For example,
x += y -= 2
first performs the subtractiony -= 2
and then adds the result tox
. - Type Coercion: If the variable and the value are of different types, JavaScript may coerce one type to another. For example, if
x
is a string and you usex += 5
,5
will be converted to a string and concatenated.