2

How can I use OR in a ternary operator? Here's what I'm trying to do:

let surname = name == "John" || "Jack" ? "Johnson" : "Smith"

nambatee
  • 1,478
  • 16
  • 27

5 Answers5

5

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

Reinier Melian
  • 20,519
  • 3
  • 38
  • 55
3

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.

Lars Blumberg
  • 19,326
  • 11
  • 90
  • 127
3

Alternatively

let surname = ["John", "Jack"].contains(name) ? "Johnson" : "Smith"
vadian
  • 274,689
  • 30
  • 353
  • 361
1

Please be aware of Operator precedence

You should use brackets to form valid condition.

let surname = (name == "John" ||  name ==  "Jack") ? "Johnson" : "Smith"
Sivajee Battina
  • 4,124
  • 2
  • 22
  • 45
1

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"
Vlatko Vlahek
  • 1,839
  • 15
  • 20