Scope and hoisting in JavaScript(JS)

Rahul Kumar Das
2 min readAug 7, 2022

Day -3 of the javascript series & today we’ll be learning about scope and hoisting

if you are new to this series check the previous part — (link)

Have you ever faced a problem in your code where you are trying to access a variable that you had declared earlier but are now unable to access at the time you want to?

It’s because of the area where you declared it.

Let’s see this situation with an example:-

→ You live in your house and if someone wants to meet you will get you at this place and not your neighbor’s. Why so? Because that’s your area or zone!!

→Similarly variables have their own area where they exist & you won’t be able to access them anywhere else. This area is known as the Scope of variables.

Scope of variables

  1. Block-scoped

Variables declared inside {}. They cannot be accessed outside this block. Variables declared with let & const are block scope.

2. Local scope

Variables declared inside a function are function/local scoped. They cannot be accessed from outside the function.

3. Global scope

Variables declared outside a function. They can be accessed from anywhere in the program. This brings us to the concept of hoisting. Hoisting is the default behavior of javascript which brings all the declaration (function declaration and variable declaration) to the top of their scope

This allows us to call function even before defining it

First console.log(foo) returns undefined and does not throw an error because variable foo is hoisted at the top which makes us use it before its declaration.

It is the same as:-

If you have any doubts drop them down in the comment box.

Thanks for reading 🙏🏻😇

Rahul

Next Part- link

--

--