Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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
229,732 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
229,732 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!