Hoisting in JavaScript

Hoisting in JavaScript

ยท

2 min read

Hoisting is a core concept of JavaScript. If you want to know what happens under the hood when we run a js code you will have to learn Hoisting first. So let's see what are the things JS engine does on our behalf when we click on that 'run' button...๐Ÿค”๐Ÿค”

What is Hoisting?

When we run a JS code, it will first create a global execution context. In this global execution, the JavaScript interpreter will scan the whole code and in this phase, it will allocate space in the memory for all the variables and functions and store them in the global object. This phase in the code execution system is called 'Hoisting'. Later we will discuss in depth how this process works for variables and functions individually.

Hoisting in Variable:

If our code contains any variable, the interpreter will allocate space for that and store that variable in the global object with the default value undefined. That's why we can access variables before even declaring them. Example:

console.log(name)
var name = "James Bond";

//Output: 'James Bond'

But it only happens with the variables declared with var, not with let or const. You can read more details about var, let, and const hoisting in this article.

Hoisting in function:

Unlike variables, a function declaration doesn't just hoist the function's name. It also hoists the actual function definition. So if we try to call a function before declaring it, it won't return undefined or any other default value, it will execute the function and then give its proper output.

You can read more about the Different Behaviours of Variable Hoisting and Function Hoisting in JavaScript from this article.

Thanks for reading. Happy coding!

ย