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 Create an Array of Objects

Sufiyaan Haroon
seal-mask
.a{fill-rule:evenodd;}techdegree
Sufiyaan Haroon
Full Stack JavaScript Techdegree Student 9,558 Points

Difference between these 2 sets of code and why one over the other:

This code is given as part of the solution:

let listProducts = prods => {
    let productNames = [];
    for (let i = 0; i < prods.length; i++) {
        productNames.push(prods[i].name)
    }
    return productNames;
}

On the other hand this is what I came up with:

let listProducts = prods => {
    return prods.map(prods => prods.name)
}

console.log(listProducts(product));

Is there anything that I might be doing wrong or is there any reason why the given solution should be used. Both give the same result btw

2 Answers

Steven Parker
Steven Parker
230,946 Points

There will rarely be only one way to solve a programming task, and using more advanced features will often make the code more compact and/or efficient.

The simple loop was probably used in this practice because it might be used by students who have not yet reached the part of the course where the more advanced map method of arrays is introduced.

Jamie Reardon
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Jamie Reardon
Treehouse Project Reviewer

Hi Sufiyaan Haroon the latter is using newer ES6 syntax so it is cleaner and easier to read than the first. Your just simply seeing two ways of achieving the same outcome which is what code is all about an that is great to see! If you wanted, for the latter you can simplify it even more to make it shorter by using an implicit return:

let listProducts = prods => prods.map(prods => prods.name);