JavaScript forEach() Method work differently in Chrome and Firefox

Viewed 1619

Here is the code:

var img = document.createElement('img');
//debugger;
console.log(img);
[1, 2].forEach(function (item) {

    console.log(img);

    img.removeAttribute("src")

    console.log(img);

    var img_src = document.createAttribute("src");
    img_src.value = '/test?id=' + item;
    img.setAttributeNode(img_src);

    console.log(img);
});

At first I ran it on Chrome and get the result:

<img src="/test?id=2">
<img src="/test?id=2">
<img src="/test?id=2">
<img src="/test?id=2">
<img src="/test?id=2">
<img src="/test?id=2">
<img src="/test?id=2">

But when I use step into in debugger or run it on Firefox,the result is the same as I thought:

<img>
<img>
<img>
<img src="/test?id=1">
<img src="/test?id=1">
<img>
<img src="/test?id=2">

Maybe the better way is to put the statement in the forEach function.

Is this a bug in developer tool of Chrome?

2 Answers

I think console.log is acting async on Firefox. It is not standardized, so the behavior might change depending on the version or the browser, it has some async issues probably related to marshaling data across process boundaries.

If you console.log a simple object and then immediately change something in the object, the console.log() does not always show the value.

Try to put img in a string, that is immutable and then print it.

Just discovered one more interesting thing. If you refresh (cmd + r) page with closed console in Firefox you'll get the same result as you have in Chrome. Just open console after refresh ;)

So it looks like a Firefox bug

Related