Ternary Operator: Concise Conditionals
The ternary operator (also known as the conditional operator) is JavaScript's only operator that takes three operands. It provides a shorthand way to write simple if-else statements, allowing you to assign a value to a variable based on a condition.
1. Syntax
The syntax of the ternary operator is:
condition ? expressionIfTrue : expressionIfFalse
condition: An expression that evaluates to a boolean (trueorfalse).expressionIfTrue: The value or expression that is returned/executed if theconditionistrue.expressionIfFalse: The value or expression that is returned/executed if theconditionisfalse.
2. How it Works
The JavaScript engine first evaluates the condition.
- If the
conditionevaluates totrue, theexpressionIfTrueis evaluated, and its result is returned. - If the
conditionevaluates tofalse, theexpressionIfFalseis evaluated, and its result is returned.
It's essentially a compact if-else statement that returns a value.
3. Examples
Let's see the ternary operator in action.
Simple Numeric Condition
Boolean Condition
String and Other Conditions
4. Why Use the Ternary Operator?
- Conciseness: It provides a very compact way to write simple conditional assignments, making your code shorter.
- Readability (for simple cases): For straightforward
if-elseassignments, the ternary operator can often be more readable than a multi-lineif-elseblock. - Conditional Assignment: It's ideal when you need to assign one of two values to a variable based on a condition.
5. When to Use / Avoid
Use when:
- You need to assign one of two values to a variable based on a simple condition.
- The expressions for
trueandfalseare relatively short and easy to understand on a single line.
Avoid when:
- The logic becomes complex or involves multiple conditions (
if-else if-else). Nested ternaries can quickly become unreadable. - You need to perform multiple actions (side effects) rather than just returning a value. In such cases, a traditional
if-elsestatement is clearer.
Exercise: Ternary Operator Challenges
Use the ternary operator to solve the following challenges. Log the final result for each.
التالي · الدرس 15 من 61
Precedence overview
قراءة 4 دقيقة
أنهيت 14 من 61 درسًا

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

