-1

I saw like many people answered that jQuery each() function isn't asynchronous. But I don't understand why this function behaves a certain way. Could anybody explain why this code:

var otherArray = [1, 2, 3, 4, 5];

var array = [];
console.log(array);

$(otherArray).each(function () {
    array[1] = $(this);
});

has this output:

enter image description here

But that code:

var otherArray = [1, 2, 3, 4, 5];

var array = [];
console.log(array);

$(otherArray).each(function () {
    // array[1] = $(this);
})

has that output:

enter image description here

Andrew Shaban
  • 129
  • 2
  • 16

1 Answers1

1

The console you see in Chrome/Firefox doesn't actually provide an exact snapshot of what an object was at the time of console.log. See this answer.

The code is indeed running synchronously. To verify this, print a "primitive" value, e.g. the length of the array:

var otherArray = [1, 2, 3, 4, 5];

var array = [];
console.log(array.length);

$(otherArray).each(function () {
  array[1] = $(this);
});

Should print 0 as expected.

Aurel Bílý
  • 7,068
  • 1
  • 21
  • 34
  • Yes, it prints length correctly. But when you need to have array itself printed, the better way to use `console.log(JSON.parse(JSON.stringify(array)));` – Andrew Shaban Jan 13 '19 at 11:10