Jump to content
kayut

Map works but forEach is not working. Why?

Recommended Posts

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 by kayut

Share this post


Link to post
Share on other sites

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);

 

Share this post


Link to post
Share on other sites

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 account

Sign in

Already have an account? Sign in here.

Sign In Now

×