开发者

Why do people declare something as null in JavaScript? [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Why is ther开发者_运维百科e a null value in JavaScript?

I don't understand what null is for. 'Undefined' as well.


It helps to appreciate the difference between a value and a variable.

A variable is a storage location that contains a value.

null means that the storage location does not contain anything (but null itself is just a special kind of value). Read that last sentence carefully. There is a difference between what null is and what null means. 99% of the time you only care about what null means.

Undefined means that the variable (as opposed to the value) does not exist.


null is an object you can use when creating variables when you don't have a value yet:

var myVal = null;

When you do this, you can also use it to check to see if it's defined:

// null is a falsy value
if(!myVal) {
    myVal = 'some value';
}

I wouldn't use it this way, normally. It's simple enough to use 'undefined', instead:

var myVal; // this is undefined

And it still works as a falsy value.

Creating Objects

When you create an object in javascript, I like to declare all my object properties at the top of my object function:

function myObject() {
    // declare public object properties
    this.myProp = null;
    this.myProp2 = null;

    this.init = function() {
        // ... instantiate all object properties
    };
    this.init();
}

I do this because it's easier to see what the object properties are right off the bat.


If a variable is not known or not initialized in the current scope it is undefined.

If you want to use a variable and indicate that it has an invalid value for instance you may want to assign it null because accessing an undefined variable will throw an error if you try to work with it (despite checking if it is undefined).

If something is undefined you also have the possibility to add it to an object. If a variable is defined but contains null you know that this variable may be used already by another part of your program.


For example, it can prepare a global variable to be used in more parts of the code.

If you start your code with var iNeedThisEverywhere = null; then you can use it inside more objects/actions in the code, but if you don't do that, then this variable will not be shared throughout the code.

Of course, you will actually put something inside that variable somewhere during the code, but since you defined this variable at the very beginning, it will be shared further anyway.


A variable holding null holds a reference to the "black hole" named null.

10 + 10 + null = null

Null is related historically to databases, http://en.wikipedia.org/wiki/Null_(SQL) (Correct me if I'm wrong here)

A variable not initiated (unknown) is undefined.

regards, /t

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜