How can I use OR in a ternary operator? Here's what I'm trying to do:
let surname = name == "John" || "Jack" ? "Johnson" : "Smith"
How can I use OR in a ternary operator? Here's what I'm trying to do:
let surname = name == "John" || "Jack" ? "Johnson" : "Smith"
Use brackets, and add name ==
in your second comparison condition, As I put first in comment this is the appropriated code
let surname = (name == "John" || name == "Jack") ? "Johnson" : "Smith"
Hope this helps
Use brackets:
let surname = (name == "John" || name == "Jack") ? "Johnson" : "Smith"
These brackets are necessary because you want to evaluate first if name
is either John or Jack before "passing" that result to the ternary operator.
Additionally, like in a all C-like languages, you have to mention name
twice, unlike the example code in your question, in order to compare it with "John" and "Jack".
If you want to avoid naming name twice, you can write instead:
let surname = ["John", "Jack"].contains(name) ? "Johnson" : "Smith"
The latter makes use of the contains()
function of arrays.
Alternatively
let surname = ["John", "Jack"].contains(name) ? "Johnson" : "Smith"
Please be aware of Operator precedence
You should use brackets to form valid condition.
let surname = (name == "John" || name == "Jack") ? "Johnson" : "Smith"
Except for brackets, you can also use array.contains for cases with a lot of names that could make the bracket code long and unreadable.
let name = "Three"
let nameList = ["One", "Two", "Three", "John", "Jack", "Vlatko"]
let surname = ["John", "Jack"].contains(name) ? "Johnson" : "Smith"
let surnameAlternate = nameList.contains(name) ? "Johnson" : "Smith"