Hoisting in Javascript
In this chapter, you will learn about what is hoisting in Javascript with examples. As we studied in the chapter execution context in javascript every function in Javascript has to pass the two phases, one is the Creation phase and Execution phase. In the Creation Phase, the following points will come under the Hoisting
- The code is scanned for function declaration. For each function, the property will be created in the variable object.
- The code is scanned for variable declaration.
Hoisting in Javascript makes it sure that the functions and variable are available to use before the execution phase starts. So that’s the reason
- Every functions and variable are hoisted in Javascript.
- The function will be defined before the execution phase starts.
- Variables are set up to undefined
- Variables will be defined in the execution phase
Let’s see the practical example for Hoisting in Javascript;
The below code snippet works good, as it is a regular function
// function declaration function fullName(firstName, lastName) { return firstName + ' '+ lastName; } let result = fullName('John','Mickel'); console.log(result); // // output // // John Mickel
Now lets us make some changes in the code snippet,
let result = fullName('John','Mickel'); console.log(result); // function declaration function fullName(firstName, lastName) { return firstName + ' '+ lastName; }
The above code snippet is returning the same output, even though we are calling the function before its declaration. If you remember that points “Whenever a function is called in the javascript, A new execution context is pushed on the top of execution context before the function gets executing”.
Now look at the function expression
// function expression const fullName = (firstName, lastName) => { return firstName + ' '+ lastName; } let result = fullName('John','Mickel'); console.log(result); // // output // // John Mickel
Now let make some changes in the code snippet, as we can see in the below example, its thrown a ReferenceError because we are assigning the function to a variable and trying to use the variable.
let result = fullName('John','Mickel'); console.log(result); // function expression const fullName = (firstName, lastName) => { return firstName + ' '+ lastName; } // // output // Uncaught ReferenceError: Cannot access 'fullName' before initialization
Now look at some variable scopes
let name = 'Stark'; console.log(name); // output // Stark
The above code snippet works fine, now make some changes in the code snippet
console.log(Name); var Name = 'John'; // output // undefined
Saved as a favorite!, I love it!
First time visiting your website, I enjoy your blog!
Bookmarked!, I love it!
First time visiting your website, I love your website!
Like!! Really appreciate you sharing this blog post.Really thank you! Keep writing.