HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

JavaScript Assignment

Assignment operators are used to assign values to JavaScript variables. While the equals sign = is the most common, JavaScript also provides several compound assignment operators that act as shortcuts for common operations.


The Assignment Operator (=)

The simple assignment operator = assigns the value of the right-hand operand to the variable on the left.

let x = 10;
let message = "Hello JavaScript";
Important: In programming, = does not mean "is equal to". It means "take the value on the right and put it into the variable on the left". To check if two things are equal, we use == or ===.

Compound Assignment Operators

Compound assignment operators combine an arithmetic operation with an assignment. They are shorthand ways to update the value of a variable based on its existing value.

Operator Example Same As
= x = y x = y
+= x += y x = x + y
-= x -= y x = x - y
*= x *= y x = x * y
/= x /= y x = x / y
%= x %= y x = x % y
**= x **= y x = x ** y

Addition Assignment (+=)

The += operator adds a value to a variable and then assigns the result back to that variable.

let score = 10;
score += 5; // score is now 15

Subtraction Assignment (-=)

The -= operator subtracts a value from a variable and then assigns the result back.

let stock = 20;
stock -= 8; // stock is now 12

Multiplication Assignment (*=)

The *= operator multiplies a variable by a value and then assigns the result back.

let price = 50;
price *= 2; // price is now 100

Division Assignment (/=)

The /= operator divides a variable by a value and then assigns the result back.

let cake = 8;
cake /= 2; // cake is now 4

Assignment with Strings

The += operator can also be used to concatenate (join) strings.

let text = "Learn ";
text += "JavaScript"; // text is now "Learn JavaScript"
Tip: Compound assignment is very common in loops and counters because it makes your code shorter and easier to read.

Key Points to Remember

  • The = operator is for assignment, not comparison
  • Compound operators (+=, -=, etc.) update a variable based on its current value
  • Using compound operators makes your code cleaner and more professional
  • The += operator works for both numbers and strings