DEV Community

Cover image for Variable and Function Hoisting in JavaScript
Arjun Junna
Arjun Junna

Posted on

Variable and Function Hoisting in JavaScript

Let's understand the concept of Hoisting in functions and variables

This is beginner-friendly content. The only prerequisite we need would be a basic understanding of variables and functions.

Before we begin let’s understand how JavaScript works. Before running any program JavaScript goes through the entire program and creates a global execution context for the program. The execution context is where the JavaScript is executed. In this global execution context, we will have 2 phases.

The first phase is the memory phase or also called the variable environment. JavaScript allocates memory in the memory phase. To all the variables it allocates the placeholder 'undefined' and to all the functions it allocates the function body itself.

The second phase is the code execution phase. Here each line of command is executed in order.

Keeping these things in mind let's dive into Hoisting

Hoisting is a phenomenon where you can access the variables and functions without any errors even before you have initialized them.

Let's walk through the below program.

console.log(a);
console.log(welcome);
welcome();
var a = 21;
function welcome() {
  console.log('Hoisting in JavaScript...');
}
Enter fullscreen mode Exit fullscreen mode

Here in this program, we are accessing the variable 'a', function named 'welcome', and then we have the function call 'welcome'. We are doing all these things before we have initialized them.

In any other programming language, this would result in many errors. But this is not the case in JavaScript.

In JavaScript, the following lines are what you will be seeing in the console.

Console Page

Here's why you will see these above lines.

As I mentioned in the intro, JavaScript before executing the program it goes through the whole program and allocates memory to each variable, and functions in the memory phase.

To our program in the global scope ->

  • JavaScript allocated the keyword 'undefined' to the variable 'a' as memory.

  • For function 'welcome' it allocated the function body itself.

Summary

JavaScript let's you access functions and variables even before they are initialized. Only function declarations are hoisted but not function expressions. Use function declarations when you want to create a function on the global scope and make it available throughout your code. Use function expressions to limit where the function is available.

Top comments (0)