JavaScript handles function and variable declarations quite differently and you must have got stuck in one of the awkward scenarios due to it.
First of all, you should be familiar with Scoping in JavaScript. If you are, then you would know already that JavaScript only has function scopes and no block scopes.
[js]
var a = ‘hello’;
console.log(a);
if(a)
{ console.log(a);
a = ‘javascript’;
}
console.log(a);
[/js]
The result is:
hello
hello
javascript
As we can see in the above example, the if block doesn’t create a new scope.
Lets go into the concept of Hoisting now. Hoisting is a way in which JavaScript deals with variable and function declarations. What actually the JavaScript interpreter does is, it pushes all your Function and Variable declarations to the top of the containing scope.
Lets understand this with a simple example:
[js]
function sum() {
calculate();
var a = 10;
var b = 20;
}
[/js]
//Now this function will be interpreted as below
[js]
function sum() {
var a, b;
calculate();
a = 10;
b = 20;
}
[/js]
Lets try some code here:
[js]
function calculate() {
sum();
multiply();
var a = 10;
function sum(){
console.log(a + b);
}
var b = 20;
var multiply = function() {
console.log(a * b);
}
}
calculate();
[/js]
The above code will throw an error : undefined is not a function. Lets see how this function is interpreted.
[js]
function calculate() {
var a, b, multiply;
function sum(){
console.log(a + b);
}
sum();
multiply();
a = 10;
b = 20;
multiply = function() {
console.log(a * b)
}
}
[/js]
As we can see, only the left hand side of the declarations is hoisted, but that is not the case with function declarations written as sum method.
The other way of declaring functions is as method multiply, in this case though the interpreter only takes the left hand side name. This results in an error undefined is not a function as multiply is undefined at the time of function call.
This is all about JavaScript Hoisting in brief.
Top comments (0)