I have a bunch of javascript functions, that trigger upon button clicks. So assuming we have two button s that trigger two methods such as:
var universal = false;
var collection = Array(); // assume it has 5 data elements( 0...4) upon page load
function next()
{
if(universal)
addToArray();
// do whatever else
}
function addToArray()
{
console.log(collection);
// perform some DOM calls,that simply Hide/change position of elements
var newElement = 'some info';
collection.push(newElement);
}
In the above addToArray() function, it is called upon when ‘next’ button is clicked and the universal variable is set to true. At this point we enter, addToArray() method and a console.log is invoked to check out ‘collection’.
This, at any given point, should be not more than 5 elements since addToArray will eventually add an element to collection but not right at the start. However, the console.log shows that collection has the new element added, which was actually supposed to be added during the addToArray method() not right off the bat.
I know this sounds really goofy, but this is what I am getting. I am trying to understand if asynchronous behavior has anything to do with it.
If you’re using Chrome, the reason is that
console.loglogs a live version of the object that updates in the console window when you change it later.If you change
…to
…or probably more usefully
…you’ll see a point-in-time version of the array.
The behavior of
console.logis actually quite tricky, although consistent once you get your head ’round it. For instance, consider this code:Live Copy | Source
If you have the console open when you run that, you see:
…and no amount of clicking on that
[1, 2, 3]will show you the"11"the code put at index0, much less the new array we put ina.But if you change the
…to
Live Copy | Source
…you see this:
…and clicking the arrow next to the array changes it to this:
first v[Array[2], 2, 3] 0: "11" 1: 2 2: 3 length: 3 __proto__: Array[0] second third…which looks a bit non-sensical.
But it does make sense, you have to think in terms of the console having a reference to the thing you asked it to output. It outputs a line for the thing, and that line is static. But because it saw that the object graph went deeper, Chrome put an arrow next to the array so you could expand it. When you click the array, the new lines added to the output are generated then, by looking at the now current version of the object, which has obviously changed since the first line was output. Tricky, eh?
In the comments, epascarello mentions using
console.dirinstead, but that just makes it even more reliably “live,” rather than being a point-in-time record.