How to test whether a variable is equal to one of five Array Values

By : eow2898

I am storing five values in an array and I need to check whether a variable I've set up is equal to one of those values. Here is what I mean:

var x = e.clientX, // horizontal mouse position
myArray = []; // I have another function that stores five values in this array

if(x == /*one of the five array values*/){
    //do something


By : eow2898


This will tell you if something is in an Array, and it's backward compatible.

function inArray(val, ary){
  for(var i=0,l=ary.length; i<l; i++){
    if(ary[i] === val){
      return true;
  return false;
// use inArray
if(inArray(yourValHere, yourArrayHere)){
  // it's in yourArrayHere so do stuff here
// use not inArray
if(!inArray(yourValHere, yourArrayHere)){
  // it's not in yourArrayHere so do stuff here
By : PHPglue

This is how you do it in ES6

var value = 5,
  myArray = [1,2,3,4,5];
myArray.some(item => item === value); // <-- true
By : Redu

You can use Array.prototype.includes, which checks if the array includes the value. Note that this is not supported on Internet Explorer, you can find the polyfill at the mentioned link. Per the documentation:


The includes() method determines whether an array includes a certain element, returning true or false as appropriate.

if(myArray.includes(x)) {
    //x is in myArray

If you want the position, you may use indexOf:


This will search for item and return the position. If not found, it will return -1. This can be applied to work with IE:

if(myArray.indexOf(x) > -1) {
    //x is in myArray

This makes sure it exists because it checks if the position is greater than -1.

By : Andrew L.

This video can help you solving your question :)
By: admin