It really comes down the the use case. For example, if you only care if the variable is of any specific value, using Array.some()
would be the best bet as it basically performs a forEach
on any iterable type and returns true at the first value the condition meets. This makes it one of the fastest ways to find out if any option meets the condition and this is an example of how it's used.
const anyOfThese = [1, 2, 14];
const doesHave0 = 0;
const doesHave1 = 1;
const doesHave14 = 14;
// checks all
const found0 = anyOfThese.some(singleValue => singleValue === doesHave0));
console.log("found0", found0);
// -> false
// check anyOfThese[0] = (1) returns without checking the rest
const found1 = anyOfThese.some(singleValue => singleValue === doesHave1));
console.log("found1", found1);
// -> true
// checks anyOfThese[0...14] until it finds singleValue === 14
const found14 = anyOfThese.some(singleValue => singleValue === doesHave14));
console.log("found14", found14);
// -> true
However, if you're storing values in some set that you want to track the total result of and you're only adding items if the set doesn't already have them for example. Using an actual Set
would be better because Sets can only have one entry for each unique value and simply adding it to the set like such.
const mSet = new Set();
mSet.add(2);
mSet.add(5);
mSet.add(2);
console.debug("mSet", mSet); // -> mSet Set {2, 5}
and if you need to know wether or not the value was added you can simply compare the size of the Set inline with the add like this
const mSet = new Set();
mSet.add(2);
const addedFive = mSet.size < mSet.add(5).size;
console.debug("addedFive", addedFive); // -> true
const addedTwo = mSet.size < mSet.add(2).size;
console.debug("addedTwo", addedTwo); // -> false
console.debug("mSet", mSet); // -> Set {2, 5}
And that <
can be any logical check, so you could say
const mSet = new Set([2]);
mSet.size === mSet.add(2); // -> returns true; didn't add 2
mSet.size !== mSet.add(2); // -> returns false; didn't add 2
mSet.size === mSet.add(5); // -> returns false; added 5
mSet.size !== mSet.add(6); // -> returns true; added 6
Or you could also use any function, so you could also say
const mSet = new Set([2]);
mSet.size === mSet.remove(2); // -> returns false; removed 2
mSet.size === mSet.remove(2); // -> returns true; didn't remove anything
The <
and >
operators make it easier to clarify what you're checking for but ===
and !==
provide a broader range of possibilities in cases where the exact change may not be important, but rather if anything did or did not change.
Just remember when writing your logic that these checks mutate your values, so that Set will really have the checked value added or removed.