Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

Possible Duplicate:
Why is there a null value in JavaScript?

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

like image 421
David G Avatar asked Apr 10 '11 18:04

David G


People also ask

What is the purpose of null in JavaScript?

The value null represents the intentional absence of any object value. It is one of JavaScript's primitive values and is treated as falsy for boolean operations.

Should you use null in JavaScript?

Only use null if you explicitly want to denote the value of a variable as having "no value". As @com2gz states: null is used to define something programmatically empty. undefined is meant to say that the reference is not existing. A null value has a defined reference to "nothing".

What does object == null mean?

Its type is object . null is a special value meaning "no value. undefined is not an object, its type is undefined.

Why is null == undefined true?

null == undefined evaluates as true because they are loosely equal. null === undefined evaluates as false because they are not, in fact, equal.


2 Answers

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.

like image 123
Rodrick Chapman Avatar answered Oct 31 '22 12:10

Rodrick Chapman


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.

like image 25
typeof Avatar answered Oct 31 '22 13:10

typeof