Hoisting is JavaScript's default behavior: moving declarations to the top. That means the following code will work in JavaScript:
bookName("ES8 Concepts");
function bookName(name) {
console.log("I'm reading " + name);
}
If you're coming from a C/C++ background, this might seem a little weird at first because those languages do not allow you to call a function before at least declaring its prototype. But JavaScript, behind the scenes, hoists the function, that is, all function declarations are moved to the top of the context. So, essentially, the preceding code is the same as the following:
function bookName(name) {
console.log("I'm reading " + name);
}
bookName("ES8 Concepts");
Hoisting only moves the declarations to the top, not the initializations. Therefore, although the preceding code works, the following code won't work:
bookName("ES8 Concepts"); // bookName is not a function
var bookName = function(name) {
console.log("I'm reading " + name);
}
This is because, as we said earlier, only declarations are hoisted. Therefore, what a browser sees is something like this:
var bookName; // hoisted above
bookName("ES8 Concepts"); // bookName is not function
// because bookName is undefined
bookName = function(name) { // initalization is not hoisted
console.log("I'm reading " + name);
}
Guess the output of the following code:
function foo(a) {
a();
function a() {
console.log("Mehul");
}
}
foo(); // ??
foo( undefined ); // ??
foo( function(){ console.log("Not Mehul"); } ); // ??
Ready to find out? Your possible answers are:
-
Mehul
undefined
Not Mehul -
Program throws error
-
Mehul
Mehul
Mehul
The output will be :
Mehul
Mehul
Mehul
Why? Because this is how your browser see this code (after applying the hoisting thing):
function foo(a) {
// the moment below function is declared,
//the argument 'a' passed is overwritten.
function a() {
console.log("Mehul");
}
a();
}
foo();
foo( undefined );
foo( function(){ console.log("Not Mehul"); } );
Once the function is hoisted, it doesn't matter what you pass in that function. It is always overwritten with the function defined inside the foo function.
Therefore, the output is just Mehul written three times.