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.

3 Answers 3

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");
}

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, is it possible to do this without an array?
@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.
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.

Comments

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.

1 Comment

What is the benefit? It's the same code as before with an extra line.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.