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 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,621 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
210,069 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,621 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.