JavaScript JavaScript Loops, Arrays and Objects Tracking Multiple Items with Arrays Useful Array Methods

Understanding of indexOf()

if (inStock.indexOf(search) > -1) { 
      print ('Yes, we have ' + search + ' in the store.'); 
    } else {
      print( search + ' is not in stock.');

I thought IndexOf() returns the index of where the value is stored in the Array?

In the video, I was expecting it to return a number which would be the position of the value inside the Array, but it returned the actual string. I just wanted to understand why that is?

3 Answers

Steven Parker
Steven Parker
173,958 Points

Your understanding of "indexOf" is correct, it returns the numeric index of the match or -1 if none is found.

What made you think it was returning a string? This code only uses it for a numerical comparison to -1. And both output statements shown here display the search string itself.

Hi Steven, thanks for the answer,

While watching the video, I saw '''print ('Yes, we have ' + search + ' in the store.'); ''' And in that video, it returned the string that was inside of the Array printed onto the webpage.

For example, Yes we have Milk in the store, instead of Yes we have 1 in the store. If that made any sense at all

Steven Parker
Steven Parker
173,958 Points

That's what I meant by "the search string itself". The output statement doesn't print the result of calling "indexOf".

Ohh, I understand it now, It was confusing me at first.

Thanks Steven!