JavaScript, Hoisting, Firefox, If/then Statements

Friday, March 21, 2014

Quick intro about JavaScript and Scoping

In most C and Java type languages a block (that is any curly brace) defines the scope of a variable or a function. However in JavaScript, scoping is at the function level. So when I define a variable inside a block (if/then statement for example) it can be used throughout the entire function it is in, including outside its defined block.

JavaScript will also take that function that is defined anywhere in a function and set its definition at the top of the function behind the scenes. This is called hoisting, and basically it allows you to call a function that is defined below the code you are calling it from.

 

So for example:

 

This works in all browsers because JavaScript hoisted the inner function to the top of the outer function behind the scenes.

If/Then statements and Firefox

The problem is in Firefox if you define a function inside an if/then statement the function no longer gets hoisted. This only happens in Firefox.

 

So in the following example, the following code works in IE and Chrome but is broken in Firefox.

 

In Firefox I get an error because it did not hoist the callHoistedFunction therefore it was not defined at the point it was being used.

ReferenceError: callHoistedFunction is not defined
var hello = callHoistedFunction();
 

So the moral of the story is never define a function inside a “if/then” or “try/catch” statement. As a matter of practice, you should probably just define all variables and functions at the top of the outer function as that is where it gets hoisted to anyways.

 

This is from Douglas Crockford’s book the “JavaScript, The Good Parts”. Pg 102.

 

In most languages, it is generally best to declare variables at the site of the first use. That turns out to be a bad practice in JavaScript, because it does not have block scope. It is better to declare all variables at the top of each function.

 

Here is his video on his book in case you were also interested.

http://www.youtube.com/watch?v=hQVTIJBZook

 

Hope this helps,

comments powered by Disqus