Assignment Operators: Storing and Updating Values
In JavaScript, assignment operators are used to assign values to variables. The most basic one is the simple assignment operator (=), but there are also several compound assignment operators that provide a shorthand for performing an operation and assigning the result back to the variable.
1. Simple Assignment (=)
The equal sign (=) is the most fundamental assignment operator. It assigns the value of the right-hand operand to the variable specified by the left-hand operand.
Examples:
2. Compound Assignment Operators
These operators combine an arithmetic (or other) operation with assignment. They provide a concise way to update a variable's value based on its current value.
| Operator | Example | Equivalent To | Description |
|---|---|---|---|
+= | x += y | x = x + y | Adds y to x, then assigns the result to x. |
-= | x -= y | x = x - y | Subtracts y from x, then assigns the result to x. |
*= | x *= y | x = x * y | Multiplies x by y, then assigns the result to x. |
/= | x /= y | x = x / y | Divides x by y, then assigns the result to x. |
%= | x %= y | x = x % y | Assigns the remainder of x / y to x. |
**= | x **= y | x = x ** y | Raises x to the power of y, then assigns the result to x. |
Examples of Compound Assignment Operators:
Addition Assignment (+=)
Subtraction Assignment (-=)
Multiplication Assignment (*=)
Division Assignment (/=)
Modulo Assignment (%=)
Exponentiation Assignment (**=)
Why use Compound Assignment Operators?
- Conciseness: They make your code shorter and often easier to read by reducing repetition.
- Readability: For simple operations,
x += 5is often clearer and faster to parse thanx = x + 5. - Efficiency: While modern JavaScript engines are highly optimized, these operators can sometimes represent a more direct instruction, potentially leading to minor performance benefits in complex scenarios.
It's a good practice to use compound assignment operators whenever you're updating a variable based on its own value.
Exercise: Applying Assignment Operators
In the editor below, perform the following tasks and log each variable's final value to the console. Follow the comments to complete the exercise!
التالي · الدرس 11 من 61
Comparison: ==, ===, !=, !==, <, >, <=, >=
قراءة 2 دقيقة
أنهيت 10 من 61 درسًا

اسأل Byte عن هذا الدرس
محادثة خاصة حول هذا الدرس. قرأ Byte الدرس كاملًا، ويجيب خلال ثوانٍ، ويُظهر القسم الذي تأتي منه كل إجابة. يمكنك السؤال بأي لغة.
الأسئلة والأجوبة
أسئلة عامة حول هذا الدرس. يجيب AI Tutor فورًا بلغتك، ويراجع فريق FreeAcademy الإجابات، ويمكن لكل المتعلمين قراءتها.

