JS Ternary Logic

Logic statements can be written in the classic If / Else / Else If syntax in Javascript. There is an option (in some cases) to write logic using a ternary operator.

%MINIFYHTML15d0e28143061169c085fc0db9b621c724%name = 'Jack'
let isUserJack = name === 'Jack' ? true : false
Code language: JavaScript (javascript)

Unlike IF/Else conditional logic, the ternary value can be returned and stored to a variable. In this case isUserJack holds the boolean value of true.

Using ternary expressions is also very clean.

Keep in mind though that a ternary expression is useful for a single conditional test. In this case we’re testing if the name is set to ‘Jack’, but we can’t check if it’s ‘Karen,’ ‘Sam,’ or ‘Eve.”

Ternaries are great ways of setting default operations… however, Javascript has another method of setting a default using the || (OR) operator. For information on using double pipes, to set default values, check out the article linked below:

About Author /

Leave a Comment

Your email address will not be published.

Start typing and press Enter to search