Modern JavaScript Development: null and undefined
In my last post on constructors and objects in JavaScript, I mentioned that the logical OR operator || was short-circuited and allowed us to set default values for arguments passed into the constructor. So we know that the argument evaluates to false if we don't pass it in to the constructor, but what value does the argument have that makes it evaluate to false?
There are three different values, or types, that a variable can have in JavaScript, null, undefined, and the value you set.
-
var isNull = null; //null type
-
var isUndefined; //undefined
-
var isNumber = 1; //neither null nor undefined, contains a value
A variable is null if you explicitly set it to the null value or if it receives a value from an expression that results in null; A variable is undefined if you declare it and haven't assigned a value to it yet. The tricky part about null and undefined is that they are equal, but are two separate types. Consider the following code.
-
var isNull = null;
-
var isUndefined;
-
alert(isNull == isUndefined);
So how do we differentiate between null and undefined variables? By using either the typeof function or the identity(===) operator. The identity operator has an evil twin (!==) that returns true if the object is not of the type you passed. The typeof function is defined in the JavaScript global object and returns a string containing the name of the type of object passed to it. The identity operator is a binary operator that compares the types of the two objects being compared and returns a boolean.
-
var isNull = null;
-
var isUndefined;
-
alert(isNull == isUndefined);
-
alert(isNull === isUndefined);
n.b. If you pass "null" as an argument to a function, typeof will return "Object", but the object will === null.
-
function defaultArgs(name, options) {
-
alert(typeof(name));
-
alert(name === null);
-
alert(name === undefined);
-
this.name = name || "unknown";
-
this.options = options || { size: 42 };
-
};
-
var instanceOne = new defaultArgs("Scott");
-
var instanceTwo = new defaultArgs();
-
var instanceThree = new defaultArgs(null, {size : 43 });
So, how does this affect the logical OR operator? Well, both null and undefined are evaluated to "false" by the || operator, but the argument is still declared in the scope of the function and you can assign a default value to it. It's important to know the distinction between null and undefined. A function call may result in a null return value, a failed function call may result in an undefined value.



Pingback: Jason Haley