Javascript: null, undefined, and undeclared

What’s the difference between a variable that is: null, undefined, or undeclared?

First up is undeclared.

A variable is undeclared when it does not use the var keyword. It gets created on the global object (that is, the window), thus it operates in a different space as the declared variables.

Example:

undeclaredVariable = 1;
var declaredVariable = 1;

function changeVariables() {
  undeclaredVariable = 2;
  var declaredVariable = 2;
  var undeclaredVariable = 3;
}

changeVariables();

undeclaredVariable; // 2
declaredVariable; //1

For more discussion on undeclared variables, checkout Mozilla’s documentation.

Now let’s move on to undefined.

Something is undefined when it hasn’t been defined yet. If you call a variable or function without having actually created it yet the parser will give you an not defined error.

Example:

var undefinedVariable; // ReferenceError: undefinedVariable is not defined
typeof undefinedVariable; // "undefined"

undefinedFunction(); // ReferenceError: undefinedFunction is not defined
typeof undefinedFunction; // "undefined"

Note that the typeof returns "undefined", therefore undefined is a primitive type.

The fix for an undefined variable or function is easy, simply define it:

var definedVariable = 'test';
typeof definedVariable; // "string"

function definedFunction(){
  return "I'm defined!"
}
typeof definedFunction // "function"

You can know if a variable is undefined with the following:

if (typeof(variable) !== "undefined") {
  console.log('variable is not undefined');
} else {
  console.log('variable is undefined');
}

Finally we’ll finish up with null.

null is a variable that is defined to have a null value.

var nullVariable = null; // null
typeof nullVariable // "object"

You probably don’t often purposefully define a variable to null, but it may be the return value of a function. Often you’ll need to gaurd against null values in your code.

You can know if a variable is null with the following:

if( variable || variable === false ) {
  console.log('variable is not null');
} else {
  console.log('variable is null');
}

I think the order “undeclared, undefined, and null” makes sense since it’s increasing order of certainty.

  • undeclared variables don’t even exist
  • undefined variables exist, but don’t have anything assigned to them
  • null variables exist and have null assigned to them
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s