DEV Community

Maher Al Musallami
Maher Al Musallami

Posted on

Ternary Operator ? True : False

What is a ternary operator

In simple words, It is a shortcut for an If statement.
You set a condition followed by a question mark, after the question mark you put some code to be executed if the the condition is truthy, And then you put a colon which will be followed by the code to be executed if the condition is falsy.
const age = 5
let grade = (age <= 5) ? "Kindergarten" : "Grade 1";

// The output should be "Kindergarten"

Convert If statement to a ternary

const number = 10
let result
if(number >= 50) {
let result = "It is true"
} else {
let result = "It is false"

// The output should be "It is false" because 10 is not greater
or equal to 50

Now let's do the same example using a ternary

const number = 10
let result = (number >= 50) ? "It is true" : "It is false"

// We should get the same output as the previous example.


condition ? true : false


Ternary is powerful operator to reduce the lines of code we have to write, As you see in the example given, We were able to reduce the code lines from 7 lines to 2 lines.

Top comments (0)