Checking Whether an Array Contains an Item

Often you will need to check whether an array contains a certain item. You can do this by using the indexOf() method. If the code does not find the item in the list, it returns a -1. The following function writes a message to the console if an item is in the week array:

function message(day){  var week = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"];  if (week.indexOf(day) != -1){    console.log("Happy " + day);  }}

Get Learning AngularJS 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.