Ternary Operator in JavaScript
The ternary operator, also known as the conditional operator, is a concise way to perform conditional assignments. It is often used to replace simple if-else statements.
Syntax
The syntax for the ternary operator is:
condition ? expressionIfTrue : expressionIfFalse
Example Scenario
Let's implement a rule where if a customer has more than 100 points, they are considered a 'gold' customer; otherwise, they are a 'silver' customer.
Step-by-Step Explanation
-
Declare a Variable to Track Points
let points = 110; -
Declare a Variable to Represent Customer Type
let type; -
Use the Ternary Operator
-
Condition:
points > 100 -
If True: Assign
'gold'totype -
If False: Assign
'silver'totypelet type = points > 100 ? 'gold' : 'silver';
-
-
Log the Result
console.log(type); // Output: 'gold'
Example Code
Here's the complete code the instructor used to explain:
// If a customer has more than 100 points
// they are a 'gold' customer, otherwise,
// they are a 'silver' customer.
let points = 90;
let type = points > 100 ? 'gold' : 'silver';
console.log(type); // Output: 'silver'
Explanation
-
Condition:
points > 100- This checks if the
pointsvariable is greater than 100. - This expression evaluates to a boolean (
trueorfalse).
- This checks if the
-
Question Mark (
?)- If the condition is
true, the value after the?is assigned to the variabletype. - In this case, if
pointsis greater than 100,typeis assigned the value'gold'.
- If the condition is
-
Colon (
:)- If the condition is
false, the value after the:is assigned to the variabletype. - In this case, if
pointsis not greater than 100,typeis assigned the value'silver'.
- If the condition is
Testing Different Values
-
For
points = 110let points = 110; let type = points > 100 ? 'gold' : 'silver'; console.log(type); // Output: 'gold' -
For
points = 90let points = 90; let type = points > 100 ? 'gold' : 'silver'; console.log(type); // Output: 'silver'
Summary
The ternary operator is a shorthand way to perform conditional assignments. It starts with a condition and evaluates to one of two values based on whether the condition is true or false. It's a powerful tool for making your code more concise and readable.
-
Syntax:
condition ? expressionIfTrue : expressionIfFalse -
Example:
let points = 90; let type = points > 100 ? 'gold' : 'silver'; console.log(type); // Output: 'silver'
Understanding and using the ternary operator can help simplify your code and make conditional assignments more straightforward.