The Best Technical Blog Ever

twitterrss

Getting Smart With: JavaScript Hoisting

JavaScript is an extremely flexible language, and will happily allow you to declare a variable almost anywhere. Because, all JavaScript declarations are Hoisted. This post will explain what is hoisting?, how does it work? and what do you need to know about it?. Before starting this topic, we have to understand the scoping concepts of JavaScript.


Scoping in JavaScript:

In general, scoping concept explains the access levels of data. A lack of understanding of this concept can lead to frustrating debugging experiences. Because, scoping concept only provides the information to the compiler whether the variables are available to a piece of code at a given time. So, we have to be aware of this concept.


Unlike other programming languages, JavaScript has two scopes - global scope and local scope(function-level scope). Variables that have global scope can be accessed from anywhere in your code. Any variable declared outside of a function belongs to the global scope, and is therefore accessible from anywhere in your code.


When a variable (local variable) is declared inside of a function using the var keyword, it is only available to the code inside of that function and any nested functions. Because JavaScript has function-level scope. As a result, code outside of that function cannot access that variable.


Also, variables that are declared inside a function without the var keyword are not local to the function. JavaScript checks the scope chain, whether the variable was previously defined. If not, it will be defined in the global scope.


JavaScript does not support block level scoping like c programming. It supports only function-level scope. Consider the following C program:


Example :
javascript hoisting


Because of block-level scope, the output of this program will be 3, 4, 3. Block scope means that variables declared in a block (such as if, for..) are not visible to code outside of that block.


Because of function level scope in JavaScript, block structure (such as for, if..) does not restrict the variable's visibility. So, the variables and parameters declared inside a function are visible everywhere within that function, even before the variable has been declared. Consider the following JavaScript program:


Example:
javascript hoisting

Output:
javascript hoisting


Here, because of the function level scope, the output of this program will be Ishida, Erica, Erica.


Now, assume that you are running a script that uses many global variable and function names. Now, you want to add another script on the same page, but there is a chance that the two scripts will use the same variable names as each other, and may conflict. Avoid this problem, by putting the code from each script inside a function, and running the function. That way, the local scope provided by the function (function level scope) will protect the variables overwriting each other in the global scope. For this, you can use self- executing anonymous function. This construct may look a little odd, but it works:


Example :
(function(msg) {
	alert(msg);  	//alerts 'Welcome to Solsoftsys!'.
})('Welcome to Solsoftsys!');

JavaScript Hoisting:

In JavaScript, we can put a variable declaration anywhere. In that case, JavaScript will just act as that variable has been declared at the top of the function. This behavior is called hoisting.


Hoisting is JavaScript's default behavior of moving all declarations to the top of the current scope. In other words; a variable can be used before it has been declared. Regardless of where a variable is declared, it will be hoisted (behind the scenes) to the top of the current scope. Thats why JavaScript allows you to declare a variable almost anywhere.


In JavaScript, function declarations are completely hoisted. Still, variable declarations are hoisted partially.


Variable Hoisting:

To understand variable hoisting, consider the following example,


Example :
javascript hoisting

As discussed before, JavaScript doesn't support block scope but instead it makes use of function scope. So it gives the following output:


Output :
javascript hoisting

This program is actually interpreted like this:


Example :
javascript hoisting

In the same program, If we remove the var z = 7; statement, Immediately, we will get a ReferenceError (z is not defined). Now consider the below example,


Example :
javascript hoisting

In this example, the output will be, x = 5 , y= 6 , z= undefined. The z value "undefined" indicates that a variable has not been assigned a value. Let's look at how JavaScript actually interprets this code in order to explain why it behaves that way.


javascript hoisting

Because JavaScript only hoists declarations, JavaScript Initializations are Not Hoisted. To make this clear, even though, the variable is initialized with the value, at the top of the scope, only the variable declaration part will be hoisted. Any assignments are left where they are. That means, the initialization part will initially be set to undefined. Thats why, the above program displays the value of z as "undefined".


Function Hoisting:

As previously mentioned, function declarations are completely hoisted. That allows you to call a function before it has been declared.


Example 1:
javascript hoisting

Example 2:
javascript hoisting

Output:
javascript hoisting

The Example2 also works as expected due to function declaration hoisting. It automatically moves function declaration to the top of the scope. So, the above code (Example2 ) is actually interpreted like this:


function display(){
    document.write("Welcome to Solsoftsys!");
}
display();

However, the function expressions with var declaration will fail spectacularly. In that case, the variable declaration for the function is hoisted before the function call, but only the declarations, not assignments made with them. Therefore, an exception is thrown for trying to call a non-function variable.


Example:
javascript hoisting

The above code is interpreted like this:


var show;
show();      // TypeError
show= function() {
  alert("Welcome to Solsoftsys!");
};

As you may have noticed, when a function expression is assigned to a variable, the rules are the same as for variable hoisting (only the variable declaration is moved to the top, while the assignment expression is left in original location)


From the above example, we can understand that the function expression can only be called after it has been defined while the function declaration can be executed both before and after it's definition.


Example:
javascript hoisting

Let's look at how JavaScript actually interprets this code,


var show;
show= function() {
  alert("Welcome to Solsoftsys!");
};
show();

Here we notice the same thing happening to our function expression as variable hoisting. It clearly explains why the first call of our function expression results in an error being thrown because the variable is undefined.  


In Function hoisting, JavaScript applies different rules depending on whether you have a function expression or a function declaration. A function declaration is fully hoisted while a function expression follows the same rules as variable hoisting.


Keypoints to remember in java

1. Java is a high level, robust, secured , platform independent and object oriented programming.... more info

Back to Basics:- Java Syntax

In this session, you are going to refresh some basic set of rules(java syntax), defining how a ... more info

Total Visits
Traffic feed status