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.

name = 'Jack' let isUserJack = name === 'Jack' ? true : false

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:

Leave a Reply

Your email address will not be published. Required fields are marked *