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!

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


JS equivalent of Python's easy way of cycling through iterables....

In Python, it's fantastically easy to search for a match by cycling through things in anything that's iterable:

if letter in 'abcdef':

if item in itemlist:

In plain JS, is there a standard pattern for looking for a match that is less verbose than something like:

for(var index = 0; index <= list.length; i += 1) {
    if(list[index] === item) {


2 Answers

Michael Hulet
Michael Hulet
47,909 Points

You could use the indexOf method to do that. If it returns -1, it isn't in the list. Otherwise, it tells you where in the list it is. This should work:

if(array.indexOf(thing) >= 0){
    // It's in the array
    // It's not in the array

Oh right, thank you, knew there was a better way.