O'Reilly logo

jQuery and JavaScript Phrasebook by Brad Dayley

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Detecting Whether an Array Contains an Item

var food = ["broccoli", "carrots", "spinach"]; var a = food.indexOf("spinach");     // a = 2 var b = food.indexOf("pizza"); // b = -1

The simplest way to check whether an item already exists in an array is to use the .indexOf(item). If the item is found, the index of the first instance is returned; otherwise, –1 is returned.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required