Surf the Dream A discourse of links and articles from Justin Avery


Using the indexOf() call in javascript allows you to…

  1. Get the index of the Array item you pass across
  2. Check to see if an item exists within an Array

If we have the following Array

var family = ['Justin', 'Laura', 'Noah', 'Darcey'];

we can then pass that array into the indexOf() function to find the index values.

family.indexOf('Justin'); // returns 0
family.indexOf('Laura'); // returns 1
family.indexOf('Noah'); // returns 2
family.indexOf('Darcey'); // returns 3

I can check to see if a value is contained within the Array by checking what the value of idexOf() returns. If the item does not exist within the Array it will return -1.

family.indexOf('Mark'); // returns -1

You can check this by putting in an IF statement with the check…

if (family.indexOf('Mark') === -1 {
  console.log('Mark is not part of the family')
} else {
  console.log('Mark is part of the family')

Side note

Thanks to Dan Needham for pointing out that I needed if (family.indexOf('Mark') === -1 instead of if (family.indexOf('Mark') = -1

Leave a Reply

Your email address will not be published. Required fields are marked *

Surf the Dream is a blog that has been running since the mid 2000's when it started on BlogSpot. Over the years it's been rebranded as (now my resume) and (which now redirects back to this site).

I offer consultation services through Simple Things, produce a range of high quality pocket notebooks(including a Solar System Notebook, Space Notebook, and a Guitar Notebook), write about the Universe and run a responsive web design knowledge hub and a RWD Weekly Newsletter.