0

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.

Justin.Mathew
  • 413
  • 5
  • 12

3 Answers3

4

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");
}
VLAZ
  • 26,331
  • 9
  • 49
  • 67
  • Thanks, is it possible to do this without an array? – Justin.Mathew Apr 14 '20 at 05:03
  • 1
    @Justin.Mathew not really. You can extract the logic to a function that takes multiple arguments. if you wish: `is = (target, ...values) => values.every(x => x === target)` so you can call it as `if (is("apple", foo, bar, baz))` but it's still using an array in the end. Comparison operators take two arguments only - on the left side and the right side, then return a single value, so you can't chain them in any useful way. – VLAZ Apr 14 '20 at 05:23
1

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.

axiac
  • 68,258
  • 9
  • 99
  • 134
0

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.

Luchux
  • 803
  • 1
  • 7
  • 17