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 trialAakash Srivastav
Full Stack JavaScript Techdegree Student 11,638 PointsExamples 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
231,184 PointsThe 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.
Aakash Srivastav
Full Stack JavaScript Techdegree Student 11,638 PointsAakash Srivastav
Full Stack JavaScript Techdegree Student 11,638 PointsThanks 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
Here , I need to provide an else statement and then , in that case , it will use lots of lines of code.