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

Loop over all methods in an object?

Say:

var foo = {
    bar: x => x * 2,
    baz: x => x / 2,
    bam: x => x + 2,
};

and then something like (I'm not very acquainted with loops in JS):

for (let method; method in foo.keys()){
    // for every method in `foo`
    console.log(foo[method](5));
};

I just started learning JavaScript, and the syntax is probably wrong. But you get the idea...

2 Answers

Sure. You could do something like this:

var foo = {
    bar: x => x * 2,
    baz: x => x / 2,
    bam: x => x + 2,
};


Object.keys(foo).forEach(method => console.log(foo[method](5)))

Thanks for replying! Is forEach an array method?

Thx