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 indexOf() -- what is happening?

I came across this code online, but I can't figure out how it is delivering the correct answer.

var locatedat = []; var enemies = ['Kylo Ren', 'Darth Vader', 'Storm Trooper', 'General Hux', 'Emperor Palpatine', 'Storm Trooper']; var enemy = 'Storm Trooper'; var enemylocation = enemies.indexOf(enemy); while (enemylocation != -1) { locatedat.push(enemylocation); enemylocation = enemies.indexOf(enemy, enemylocation + 1); } console.log(locatedat); // 2, 5

I get how the script returns 2, but how does it figure out 5?

1 Answer

Steven Parker
Steven Parker
243,658 Points

The optional 2nd argument to "indexOf" tells it to look only at values with an index as high or higher than that argument. So if the first item found was at index 2, then the next search will begin at 3 and find 5. Since there are no matches after 5, the third search will return -1 and end the loop.