Ternary operator
JavaScript Ternary Operator
The JavaScript ternary operator is a concise way to write conditional statements in JavaScript. It is often used as a shorter alternative to if-else statements.
Syntax
The syntax of the JavaScript ternary operator is as follows:
condition ? expression1 : expression2;
The condition is evaluated, and if the condition is true, expression1 is executed. If the condition is false, expression2 is executed.
Examples
Here are a few examples of using the JavaScript ternary operator:
Parentheses make the code more readable, so we recommend using them.
const age = 22; const canVote = (age >= 18) ? 'Yes' : 'No'; console.log(canVote); // Output: Yes const number = 7; const isEven = (number % 2 === 0) ? true : false; console.log(isEven); // Output: false const greeting = 'Good ' + ((new Date().getHours() < 12) ? 'morning' : 'afternoon'); console.log(greeting); // Output: Good morning or Good afternoon, depending on the current time
In the first example, the condition `age >= 18` is evaluated. If the condition is true, the value `'Yes'` is assigned to the `canVote` variable, otherwise the value `'No'` is assigned.
In the second example, the condition `number % 2 === 0` is evaluated. If the condition is true, the value `true` is assigned to the `isEven` variable, otherwise the value `false` is assigned.
In the third example, the condition `new Date().getHours() < 12` is evaluated. If the condition is true (i.e., it's before noon), the string `'morning'` is concatenated with the string `'Good '`, otherwise the string `'afternoon'` is concatenated.
Multiple `?`
A sequence of question mark operators ? can return a value that depends on more than one condition.
let age = prompt('age?', 18); let message = (age < 3) ? 'Hi, baby!' : (age < 18) ? 'Hello!' : (age < 100) ? 'Greetings!' : 'What an unusual age!'; alert( message );
It may be difficult at first to grasp what’s going on. But after a closer look, we can see that it’s just an ordinary sequence of tests:
- The first question mark checks whether age < 3.
- If true – it returns 'Hi, baby!'. Otherwise, it continues to the expression after the colon “:”, checking age < 18.
- If that’s true – it returns 'Hello!'. Otherwise, it continues to the expression after the next colon “:”, checking age < 100.
- If that’s true – it returns 'Greetings!'. Otherwise, it continues to the expression after the last colon “:”, returning 'What an unusual age!'.
Here’s how this looks using if..else:
if (age < 3) { message = 'Hi, baby!'; } else if (age < 18) { message = 'Hello!'; } else if (age < 100) { message = 'Greetings!'; } else { message = 'What an unusual age!'; }
Non-traditional use of `?`
Sometimes the question mark ? is used as a replacement for if:
let company = prompt('Which company created JavaScript?', ''); (company == 'Netscape') ? alert('Right!') : alert('Wrong.');
Depending on the condition company == 'Netscape', either the first or the second expression after the ? gets executed and shows an alert.
We don’t assign a result to a variable here. Instead, we execute different code depending on the condition.
It’s not recommended to use the question mark operator in this way.
The notation is shorter than the equivalent if statement, which appeals to some programmers. But it is less readable.
Here is the same code using if for comparison:
let company = prompt('Which company created JavaScript?', ''); if (company == 'Netscape') { alert('Right!'); } else { alert('Wrong.'); }
Our eyes scan the code vertically. Code blocks which span several lines are easier to understand than a long, horizontal instruction set.
The purpose of the question mark operator ? is to return one value or another depending on its condition. Please use it for exactly that.
Use `if` statements when you need to execute different branches of code.
Benefits
The JavaScript ternary operator has several benefits:
- Conciseness: It allows you to write conditional statements in a more compact and readable way.
- Flexibility: It can be used in a variety of scenarios, from simple assignments to complex expressions.
- Reduced repetition: It can help avoid repeating similar code blocks in if-else statements.
Key Takeaways
- The JavaScript ternary operator is a concise way to write conditional statements.
- Its syntax consists of a condition, followed by a question mark, an expression for the true case, a colon, and an expression for the false case.
- It can be used for simple assignments or more complex expressions.
- The ternary operator can help write more readable and concise code, reducing repetition.
Comments
Post a Comment