Sunday, December 21, 2014

Hoisting in JavaScript

Hoisting in JavaScript

Moving the declaration of variable and function at the top is called Hoisting.
First function declaration is hoisted and then variable declaration is hoisted.

Example 1

console.log(a); // undefined
var a = 10;
console.log(a); // 10
view raw gistfile1.js hosted with ❤ by GitHub
In the above program JavaScript compiler moves declaration of variable at the top.

var a;
console.log(a); // undefined
a = 10;
console.log(a); // 10
view raw gistfile1.js hosted with ❤ by GitHub
Example 2

console.log(a); // undefined
var a = 10;
console.log(a); // 10
greet(); // "Hello"
function greet() {
console.log("Hello");
}
view raw gistfile1.js hosted with ❤ by GitHub
In the above program JavaScript compiler moves declaration of variable and function at the top.

function greet() {
console.log("Hello");
}
var a;
console.log(a); // undefined
a = 10;
console.log(a); // 10
greet(); // "Hello"
view raw gistfile1.js hosted with ❤ by GitHub

No comments:

Post a Comment