Assignment & Ternary Operator
Assignment & Ternary Conditional Operator
Assignment operators update the value stored inside variables, while the ternary operator provides a concise, elegant way to write inline conditional expressions.
1. Assignment Operators
The basic assignment operator is the equals sign (=). JavaScript also provides compound assignment operators that combine an arithmetic operation with assignment:
| Operator | Name | Equivalent To | Example |
|---|---|---|---|
= | Simple Assignment | x = y | let score = 100; |
+= | Addition Assignment | x = x + y | score += 10; (Now 110) |
-= | Subtraction Assignment | x = x - y | score -= 20; (Now 90) |
| *`=`** | Multiplication Assignment | x = x * y | score *= 2; (Now 180) |
/= | Division Assignment | x = x / y | score /= 3; (Now 60) |
%= | Modulus Assignment | x = x % y | score %= 7; (Now 4) |
| `=`** | Exponentiation Assignment | x = x ** y | score **= 2; (Now 16) |
String Concatenation Assignment (+=):
2. The Ternary Operator (condition ? expr1 : expr2)
The ternary operator is the only operator in JavaScript that takes three operands. It serves as a compact, inline shortcut for an if...else statement:
Comparison: if...else vs. Ternary
Why Developers Love the Ternary Operator:
Because the ternary operator is an expression (it returns a value), you can assign it directly to a const variable, pass it as a function argument, or embed it directly inside template literals:
3. Nested Ternary Operators (Use With Caution!)
You can chain ternary operators for multiple conditions, but be careful not to hurt code readability:
if...else or switch statement for better team readability.Practice Quiz
x += 5?const result = (10 > 5) ? "Yes" : "No";?if...else when initializing const variables?x after running let x = 12; x %= 5;?Conditional Statements: if, else if, else
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Logical Operators | Conditional Statements: if, else if, else |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.