J.Doe
J.Doe

Reputation: 17

Console log behaviour regarding array in a function

What am i missing here? Cant get it why my console behaves differently depending on either while loop is there or not?

function findPath(){
  var openArr = [];
  var closeArr = [];
  var morefun = {};
  var morefun1 = {};
  var morefun2 = {};
  morefun.f = 1;
  morefun1.f = 2;
  morefun2.f = 3;
  openArr.push(morefun1);
  openArr.push(morefun2);
  openArr.push(morefun);
  console.log(Array.isArray(openArr));
  console.log(openArr);
  console.log(openArr.length);

    while (openArr.length){
    var current = openArr.pop();
    closeArr.push(current);
    }
}
findPath();

Im getting from console.log(openArr)

 [Object, Object,Object]
 length: 0  // when while loop is there.

And getting

 [Object, Object,Object]
 0:Object
 1:Object
 2:Object
 length:3 // without while loop

It doesent seem to be Chrome only thing as my Firefox console shows similar results - when i click on an array for details i get length:0 with loop and length:3 w/o. Am i missing smth with execution order?

Upvotes: 1

Views: 340

Answers (1)

Mike Cluck
Mike Cluck

Reputation: 32511

When you write something to the console, it creates a string that represents the state of the object at that time. However, it also stores a reference to the actual object and that's what you're presented with in the console.

Expanding that reference shows it's actual state where as the string shows it's state at the time of printing. If you want to see the complete state of an array with each console.log you could convert it to JSON.

console.log(JSON.stringify(openArr, null, 2));

Example:

var arr = [{ n: 1 }, { n: 2 }, { n: 3 }];
console.log(arr); // [Object, Object, Object]
arr.pop();
// Expand the array and you'll only see 2 elements

var arr2 = arr.slice(0);
// To see the full state of the array, serialize it
console.log(JSON.stringify(arr2, null, 2)); // [ { "n": 2 }, { "n": 3 } ]
console.log(arr2); // [Object, Object]
arr.pop();
// Expand the array and you'll only see 1 element

Upvotes: 2

Related Questions