ES6 Ternary Operator
The ternary operator is a concise and readable way to express conditional statements in JavaScript. It has the following syntax:
expression ? value_if_true : value_if_false
123let number = 10; let numType = number % 2 == 0 ? "Even" : "Odd"; console.log (numType);
Here the statement of interest is number % 2 == 0 ? "Even" : "Odd"
.
If you look closely, you will notice that it follows the syntax of the ternary operator. Here number % 2 == 0
is the expression to be evaluated. The operator returns "Even"
if the expression is true, and "Odd"
if the expression is false. In turn, the returned value is stored in the variable numType
.
FizzBuzz problem using ternary operator (not if-else):
123456789for(let i = 1; i < 17; i++) { console.log( i % 3 == 0 && i % 5 == 0 ? "FizzBuzz" : ( i % 3 == 0 ? "Fizz" : ( i % 5 == 0 ? "Buzz" : i ) ) ); }
Task
Write a conditional using the ternary operator that returns the square of i
if i
is less than 5 otherwise the cube of i
.
Tack för dina kommentarer!
Fråga AI
Fråga AI
Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal
Awesome!
Completion rate improved to 2.7
ES6 Ternary Operator
Svep för att visa menyn
The ternary operator is a concise and readable way to express conditional statements in JavaScript. It has the following syntax:
expression ? value_if_true : value_if_false
123let number = 10; let numType = number % 2 == 0 ? "Even" : "Odd"; console.log (numType);
Here the statement of interest is number % 2 == 0 ? "Even" : "Odd"
.
If you look closely, you will notice that it follows the syntax of the ternary operator. Here number % 2 == 0
is the expression to be evaluated. The operator returns "Even"
if the expression is true, and "Odd"
if the expression is false. In turn, the returned value is stored in the variable numType
.
FizzBuzz problem using ternary operator (not if-else):
123456789for(let i = 1; i < 17; i++) { console.log( i % 3 == 0 && i % 5 == 0 ? "FizzBuzz" : ( i % 3 == 0 ? "Fizz" : ( i % 5 == 0 ? "Buzz" : i ) ) ); }
Task
Write a conditional using the ternary operator that returns the square of i
if i
is less than 5 otherwise the cube of i
.
Tack för dina kommentarer!