Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript

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':
    print(letter)

if item in itemlist:
    print(item)

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) {
        console.log(item);
        break;
    }
}

?

2 Answers

Michael Hulet
Michael Hulet
47,842 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
}
else{
    // It's not in the array
}

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