Possible Duplicate:
Why is there anull
value in JavaScript?
I don't understand what null is for. 'Undefined' as well.
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.
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".
Its type is object . null is a special value meaning "no value. undefined is not an object, its type is undefined.
null == undefined evaluates as true because they are loosely equal. null === undefined evaluates as false because they are not, in fact, equal.
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 you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With