Javascript Fundamentals:  Variables and Hoisting

Tags: javascript

Programmers young and old and new and old benefit from learning and relearning the fundamentals.  So then…here is a quick review of variables and hoisting. 

undefined vs. null

When will a variable be null, when will it be undefined? Are they the same? 

Code

Result

Comments

var someVar;

typeof someVar = undefined

Javascript does not know the type

var someVar = null;

typeof someVar = object

Javascript assumes the variable is an object if it was set to null

undefined == null;

true

Their values are equal

undefined === null;

false

Their types are not equal

 

The convention is to not declare variables without initializing them.  Initialize them so you know what they are.

Hoisting

Hoisting describes a behavior of the javascript compiler.  Before the actual code execution the compiler passes through the code and locates all identifiers.  All the identifiers are now known by the compiler.  Then the code executes.  Let's see some example situations.

Code

Result

Comments

console.log(someVar);

ReferenceError

someVar  has not been defined

console.log(someVar);

var someVar = 100;

undefined

someVar  has been defined because of hoisting, but it is not initialized at the time of console.log

var answer = x + y;

var x = 1;

var y = 2;

console.log(answer);

 

NaN

x and y have been defined because of hosting but not initialized.  undefined + undefined is not a number

doTheThing();

function doTheThing () {

   console.log(‘The Thing’);

}

The Thing

The function doTheThing is known because of hoisting

doTheThing();

var doTheThing  = function () {

   console.log(‘The Thing’);

}

TypeError

The variable doTheThing is known because of hoisting but not initialized

 

Hoisting is pretty tricky isn’t it?  That’s why it is recommended to not rely on it.  Better to declare things before you try to use them.

a Plunk of the examples  https://plnkr.co/dE1AUVG0QvqGwaYawbVF

No Comments

Add a Comment