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.

Get jQuery and JavaScript Phrasebook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.