Pretty weird ES6 issue

Posted 1 year ago by bart

Hey guys,

a colleague of mine found a pretty interesting ES6 issue that is very easy to reproduce. You can add the following lines of code somewhere in a script tag.

const data = [{title: 'a'}, {title: 'b'}, {title: 'c'}];
console.log(data);
data.forEach((d, index)=> {
    d.title = 'd';
});

What I expected as a result of console.log() was an array of three objects having titles of "a", "b" and "c". But what we actually got was an array of three objects with a title of "d". Why? Do you have any explanation for it? Why does console.log() gets called after the foreach loop?

Thanks and kind regards!

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.