Categories
JavaScript Answers

How to check if item is in array in JavaScript?

Spread the love

To check if item is in array in JavaScript, we use the indexOf method.

For instance, we write

const blockedTile = ["118", "67", "190", "43", "135", "520"];

if (blockedTile.indexOf("118") !== -1) {
  // ...
}

to call blockedFile.indexOf with the item we’re looking for to see it’s in the blockedFile array.

It returns the index of the item if it exists and -1 otherwise.

If it returns something bigger than -1, then the item is found.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.