Justin.Mathew
Justin.Mathew

Reputation: 481

Javascript - if multiple conditions equal something

I want to know how to write,if(foo === 'apple' && bar === 'apple'){then do something} without having to repeat the word apple. So if I am checking many conditions are equal to something. I would write this something if(foo && bar === 'apple') but that just checks if foo exists and bar === 'apple'. Is there a way to do this?

Basically reduce the necessity to repeat the word apple.

Upvotes: 0

Views: 95

Answers (3)

VLAZ
VLAZ

Reputation: 29007

You can use Array#every to verify all your conditions:

let foo = "apple";
let bar = "apple";
let baz = "banana";

if ([foo, bar].every(x => x === "apple")) {
  console.log("foo and bar are apple");
} else {
  console.log("foo and bar are NOT apple");
}

if ([foo, bar, baz].every(x => x === "apple")) {
  console.log("foo, bar, and baz are apple");
} else {
  console.log("foo, bar, and baz are NOT apple");
}

You can extract this check to a small helper function to make things easier, too:

let foo = "apple";
let bar = "apple";
let baz = "banana";

const is = target => x => x === value;

if ([foo, bar].every(is("apple"))) {
  console.log("foo and bar are apple");
} else {
  console.log("foo and bar are NOT apple");
}

if ([foo, bar, baz].every(is("apple"))) {
  console.log("foo, bar, and baz are apple");
} else {
  console.log("foo, bar, and baz are NOT apple");
}

Upvotes: 4

axiac
axiac

Reputation: 72226

A solution is to wrap all the variables into an array and to use Array.every():

if ([foo, bar].every((val) => val === 'apple')) {
   ...
}

It is good if you need to check 5-6 values or more but for only two values I think your original code is easier to read.

Upvotes: 1

Luchux
Luchux

Reputation: 795

You can set a variable and check against the variable if you don´t want to repeat your self.

let value = 'apple'; 
if(foo === value && bar === value){then do something}

note: better to rename value to a name that represent your variable better in your problem domain.

Upvotes: 0

Related Questions