简体   繁体   中英

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.

The ternary syntax is conditional ? true : false 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)) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM