ternary Operator

ternary Operator

  • Used as a shortcut for the if statement
condition ? expression that is run if condition is true : expression that is run if condition is false

Example

const isLactoseIntolerant = true

const milkType = isLactoseIntolerant ? "almond" : "dairy"
console.log(milkType)

JS Bin on jsbin.com

Exercise

Rewrite the following if..else statement using a ternary operator:

let yearOfBirth = 2001

if (yearOfBirth <= 2002) {

  console.log('you will be old enough to vote in 2020')

} else {

  console.log('Sorry, you will not be old enough to vote next year')

}

JS Bin on jsbin.com