2

There is files array in my code. When i adds new file, its showing incorrect length of array. But, if i checked the length with settimeout its showing correct length.

console.log('row.myDocuments: ', row.myDocuments);  
console.log('length: ', row.myDocuments.length);

Getting results in console like this,

enter image description here

Every time when i add new file, the length getting in console is (actual length -1)

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Mangesh Daundkar
  • 1,026
  • 1
  • 15
  • 20

1 Answers1

9

This is related to Chrome dev tools. You see the little "i" in a blue square next to "[]"? If you hover it with your mouse, it says "value below was evaluated just now". It means that at the time you logged your array (which is actually a javascript Object), it was empty, but later Chrome detected a change, and updated the array in the console.

(And that is only if you expand it using the little arrow, you can see the array was empty at the time it was logged since it looks like this "[]", otherwise it would have looked like this "[{...}]").

Chrome updates object when you log them, but not simple values. Array.length is a number, so when you log it, it gives you its value (0), and if Array.length changes later, it will not update the console; but if you log it after the change (as with your timeout), it will log the more recent value.

Alex D
  • 456
  • 4
  • 8
  • Thanks Alex... But is there any alternative to settimeout. Actually, i'm expecting actual value without settimeout. – Mangesh Daundkar Nov 14 '18 at 10:44
  • You need the actual value in the console? In the code it will always be the right value, if the array is empty then its length will always be 0. What you could do instead, is log a copy of the array so that the logged array and its length match. So change console.log(myArray) to console.log(myArray.slice()). Another option is to add a breakpoint in the "Sources" section of chrome devtools, where it will show the most recent value next to the variable name. – Alex D Nov 14 '18 at 11:00