billygreen
billygreen

Reputation: 223

Using the ternary operator instead of if/else?

I have recently been learning about the ternary operator, and how it is a good shortcut instead of using if/else operator.

I've been practicing and this is a program that that configures what type of school someone should go to based on their age.

However, when I run the code, it is not working.

var age = 15;

function whichSchool(age) {
  return (age < 13) ? "Elementary School"
       : (age >= 13 && age <= 18) ? "Secondary School"
       : (age > 18) ? "University"
}

console.log(whichSchool(15))

It says: unexpected token {.

Any help is appreciated.

Thank you.

Upvotes: 1

Views: 1511

Answers (1)

Obsidian Age
Obsidian Age

Reputation: 42374

The ternary syntax is conditional ? true : false. You've combined multiple if conditional ternaries here, though no logic for if none of the conditionals are met. To correct this, add fallback behavior of : false after your final conditional:

var age = 15;

function whichSchool(age) {
  return (age < 13) ? "Elementary School"
       : (age >= 13 && age <= 18) ? "Secondary School"
       : (age > 18) ? "University"
       : "None"
}

console.log(whichSchool(15))

Note that this false logic will never actually be met though with the combination of conditionals above (someone is either under 13, between 13 and 18 or over 18), and you'd be better off simply having : "University" as the default in this instance:

var age = 15;

function whichSchool(age) {
  return (age < 13) ? "Elementary School"
       : (age >= 13 && age <= 18) ? "Secondary School"
       : "University"
}

console.log(whichSchool(15))

Upvotes: 2

Related Questions