Sometimes, we’ve to check variable equality against a list of values in JavaScript.
In this article, we’ll look at how to check variable equality against a list of values in JavaScript.
Use the Array.prototype.indexOf Method
We can use the JavaScript array’s indexOf
method to check if a value is included in the list of values in the array.
For instance, we can write:
let foo;
//...
if ([1, 3, 12].indexOf(foo) > -1) {
//...
}
We have the foo
variable and we check if foo
is 1, 3 or 12 by putting those values in an array and then call the indexOf
method of the array with foo
.
Then if it returns a number bigger than -1, we know foo
is one of the values listed in the array.
Use the Array.prototype.includes Method
Another array method we can use to check if a variable is one of the values in a list is to use the includes
method.
For instance, we can write:
let foo;
//...
if ([1, 3, 12].includes(foo)) {
//...
}
We call includes
the way we call indexOf
.
If includes
returns true
, then we know foo
is one of the values in the array.
Conclusion
We can put the list of values we want to check in an array and then use the includes
or indexOf
method to check if the variable is in the array.