0

I was doing a task in JavaScript and I notice when i try to print only half array the final array is being printed. Here the code:

let a = [];
for (let i = 1; i < 5; i++) {
  if (i === 2) console.log(a)
  a.push(i)
}

Here in output instead of printing array with only 1 element it is printing array with every element from 1 to 5. My question is why this is happening?

3limin4t0r
  • 19,353
  • 2
  • 31
  • 52
  • you are modifying the array where you are looping through. But anyway if you run the script, of course it will log the array only at the second iteration of the loop... when you only added one element yet – Diego D Jul 18 '22 at 12:21
  • Did you run the code snippet? What output were you expecting to see? – jarmod Jul 18 '22 at 12:22
  • 1
    As noted in the duplicate, the browser's log shows a reference to the array, not the array itself as it was when you logged it, and when you expand it, it shows the current value of the array, which has all of the values. Hover over the blue `i` in the console. – Heretic Monkey Jul 18 '22 at 12:25

0 Answers0