The first example is a declaration. You have declared a variable with the identifier foo
. You haven't given it a value yet, so it will be undefined
:
var foo;
console.log(foo); //undefined
The second example is a declaration and an assignment. You have assigned an empty object literal to the variable with the identifier foo
. As noted in the comments, this is effectively short for:
var foo;
console.log(foo); //undefined
foo = {};
console.log(foo); //Object
The third example is another declaration and another assignment. You have assigned a different object literal to foo
.
Edit (see comments)
The behaviour of your code is slightly different depending on whether you intended each example to run as an independent program, or as written (one program).
If you treat is as it's written:
Because variable declarations in JavaScript are hoisted to the top of the scope in which they appear, redeclaring variables has no effect. So the first line declares a variable foo
.
The second line assigns an empty object literal to foo
, and the third line assigns a different object literal to foo
. Both of these assignments apply to the same foo
.
What effectively happens is this:
var foo;
foo = {}; //No `var` keyword
foo = {first:"number_one"}; //No `var` keyword
If you treat each line as a separate program:
The first program declares a variable named foo
. It's value is undefined
.
The second program declares a variable named foo
, and then assigns an empty object literal to it.
The third program declares a variable named foo
and then assigns an object literal with one property to it.