kayut Posted June 18, 2018 Share Posted June 18, 2018 (edited) Hey, Can some one please explain to me why this works: let myNames = ['apple', 'orange', 'lemon']; let output = myNames.map(function(item){ return item; }); console.log(output); But the same code with forEach doesn't work? let myNames = ['apple', 'orange', 'lemon']; let output = myNames.forEach(function(item){ return item; }); console.log(output); Isn't it that myNames is an array and forEach is a built-in method of Array? Why is that the forEach is not working? Thanks Edited June 18, 2018 by kayut Link to comment Share on other sites More sharing options...
dsonesuk Posted June 18, 2018 Share Posted June 18, 2018 One creates a new array and insert each item from old to new and applies to a variable, the other loops through old array elements. It won't produce the same result unless it pushes the items into a new already created array. To produce duplicate array from both var myNames = ['apple', 'orange', 'lemon']; let output = myNames.map(function(item) { return item; }); console.log(output); let output2 = []; myNames.forEach(function(item2) { output2.push(item2); }); console.log(output2); Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now