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 JavaScript Array Iteration Methods Array Iteration Examples Using forEach()

Aakash Srivastav
seal-mask
.a{fill-rule:evenodd;}techdegree
Aakash Srivastav
Full Stack JavaScript Techdegree Student 11,638 Points

Examples using forEach()

I have tried the example he provided without using any external array :

const fruits = ['apple' , 'pear' , 'cherry'];
fruits.forEach((fruit,index,array) => {
    array[index] = fruit.toUpperCase();
});
console.log(fruits);

Is this good approach ?

1 Answer

Steven Parker
Steven Parker
231,275 Points

The video code created a new array with capitalized names, but this code modifies the original one. Both examples are good approaches to achieving different results. In a real-life situation, only one would be appropriate, and that would be determined by the task criteria.

But for the purpose of simply demonstrating array methods, your example has the advantage of illustrating a use for all 3 callback arguments. :+1:

Aakash Srivastav
seal-mask
.a{fill-rule:evenodd;}techdegree
Aakash Srivastav
Full Stack JavaScript Techdegree Student 11,638 Points

Thanks Steven Parker . I think that , this approach can be used only when we want to bring changes in all the items of the array. For ex , if there is an array with lots of students name and we want to filter only those students whose name starts with "S" , then we can't use this method , because for that , we need an "else" statement too

const names = ['Selma', 'Ted', 'Mike', 'Sam', 'Sharon', 'Marvin'];
let namesWithS = [];
names.forEach((name, index, arr) => {
    if (name.startsWith('S')) {
        arr[index] = name;
    }
});
console.log(names);

Here , I need to provide an else statement and then , in that case , it will use lots of lines of code.