9

I've been testing some JavaScript using the Google Chrome version 28.0.1500.95 m console and am looking for a bit more understanding of how it works: Have a look at the code below:

var obj = {
    a: 99,
    f: function() { }
}

console.log(obj.a)
console.log(obj.z)    
console.log(obj)

o.z = 100;

Demo

This outputs the following results:

99 
undefined 
Object {a: 99, f: function}
a: 99
f: function () { }
z: 100
__proto__: Object

My question is, why is z visible in the results when it wasn't declared until after the log?

I'm assuming this is something with how the console works and not some weird scoping rule in JavaScript, that I'm unaware of?

Can anyone tell me what's happening here please?

davy
  • 4,474
  • 10
  • 48
  • 71

1 Answers1

11

The object in the console initially is shown as Object and expanded when you click on the arrow.

There is an i-icon when you expand the Object, when you hover it you'll see the answer:

object state below is captured upon first expansion

What you see after the expansion is the state of the object at the time of the expansion, not the state at the moment when you call log()

Dr.Molle
  • 116,463
  • 16
  • 195
  • 201
  • 3
    Lol even at version 28 the only improvement they have done is to add pretty much undiscoverable tooltip that this is happening. – Esailija Aug 07 '13 at 08:46
  • I'm doing array sort: If they're different (ie: I'm sorting an array here), does that mean I've written my script logic wrong? Because what is first shown is not the same order as what is shown in the expanded list. – ericjam Mar 30 '14 at 00:30
  • the output of the console has nothing to do with your script-logic(you may e.g. log the joined array to get the expected order in the log) – Dr.Molle Mar 30 '14 at 01:10
  • btw- firefox does exactly the same – andig May 05 '14 at 14:56