Definition vs initialization

What's the difference between declaration, definition and initialization? Example:

// Is this a declaration?
var foo;

// Did I defined object in here (but it is empty)?
var foo = {};

// Now that object is initialized with some value?
var foo = {first:"number_one"};

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.


You got it right.

var foo;        // Is this a declaration ?

Yes, you declared that there's a variable named foo , but didn't define foo (so foo is undefined).

var foo = {}    // Did I defined object in here (but it is empty) ?

Yes, now you "defined" foo ... it has a value, it is no longer undefined. var foo = 5 also counts as "defining" it.

var foo = {first:"number_one"}  // Now that object is initialized with some value ?

You could say that it's "initialized," but that's really just semantics. "Declared" and "defined" are a bit more meaningful.


运行下面的代码:

var foo;
console.dir(foo);
var foo = {};
console.dir(foo);
var foo = {first:"number_one"};
console.dir(foo);
链接地址: http://www.djcxy.com/p/95030.html

上一篇: html / javascript / php:我如何使用“全局变量”?

下一篇: 定义vs初始化