JavaScript Ternary Operators

The ternary or conditional operator is the only Javascript operator that takes three operands. This operator is a shortcut for the if statement. It tests the condition and returns one value or expression if it is true and another if it is false.

The example below shows there is a condition followed by a question mark. If it is true it will return the first expression but if it is false it will return the second expression. The two expressions are separated by a colon.

condition ? one : two

Below I will show you an example with an if statement.

Var equals 2020. If the year is more than or equal to 2021 I’ve console.log “Can’t wait to see what the future holds.” else console.log “Don’t look back.”

Once it is run “Don’t look back” is returned. If the year is changed to 2022 we’ll get “Can’t wait to see what the future holds” in return. See below.

However there is a different way to do this. We can use a ternary operator.

If year is more than 2021 is the condition followed by the question mark. if the condition is true it will print “Can’t wait to see what the future holds”. If it is false it will return “Don’t look back.”

The second way is a more sufficient way of doing something if there is a simple if else statement. It’s shorter, straight to the point and easy to read.

thanks for reading.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store