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


Greg Nemes
Greg Nemes
4,261 Points

Possible to avoid for loop and if statement in playToken method?

Instead of looping through each space to set the targetSpace to the last space in the loop, and then checking if the space.token is null, could you use the following instead?

const columnSpaces = this.board.spaces[token.columnLocation];
const targetSpace = columnSpaces.filter(space => space.token === null)[columnSpaces.length - 1];

I think this produces the same result, although I'm not 100% sure. Is there a reason why this would be less desirable than the for loop and the if statement? I could see the for>if being more legible.

If there was a performance concern, would one solution be better than the other?

1 Answer

Daniel Medina
Daniel Medina
13,863 Points

Hello Greg,

Filtering / mapping / reducing is another approach that is often taken when iterating. As I understand it, these methods of iteration are primarily used in Functional JavaScript rather than regular Object Oriented JavaScript.

Readability is one reason for using for / if approach compared to filtering and arrow functions. Another reason is performance; if you are concerned with performance, try sticking to a regular for loop with if statements.

An alternative approach is to use a foreach loop.

If you're interested, here are some links that talk about the performance issues involved with each approach:


Greg Nemes
Greg Nemes
4,261 Points

Thanks Daniel!

I initially thought that filter may have been more efficient, because it seems more compact, but I now see that it's compactness makes it less efficient.