Scoping and Hoisting in JavaScript

Posted By :Ishaan Madan |31st July 2018

For a beginner in JavaScript, it's quite usual to come across the term "Hoisting in JavaScript", Before going into further details lets, have a look at an example. Below, a function is created and invoked:

function cowSays(sound){
  console.log(sound);
}
cowSays('moo');

 

As one may expect,  when the function "cowSays" is invoked by passing a string 'moo' as an argument, the function logs the passed string and the output in the case is 'moo'.

cowSays('moo');
// moo

 

But, what if we try to invoke the function before it is actually declared?

cowSays('moo');
function cowSays(sound){
  console.log(sound);
}

 

Unexpectedly, the function gets called again and 'moo' is returned as the output to the console.

cowSays('moo');
// moo

 

This is what is known as hoisting in JavaScript.

So, what did we just see? Usually, people describe hoisting as declarations moving at top of the code. Although, it is something that appears to be happening. But technically, the code never moves anywhere. Such magic doesn't exist yet. 

What actually happens is the declarations of the functions and variables are added to the memory at the time of compilation.


In the above given example, since the function declaration is added to the memory during the compile phase. In the example above, since the declaration of functions is added to the memory at the compile time, We were able to access them even before the place they were declared.

Now, Let's have a look at another example with a different variable:

Typically,  one should declare then initialize the variable,  and then should attempt to make use of it:

var a = 3;
console.log(a);
// 3

 

However, what will happend, if the variable is declared at the bottom of the code?

a = 3;
console.log(a);
var a;
// 3

 

The example above logs the output as '3'

But, How about the below example in which we declare and initialize  the variable right at bottom of the code?

console.log(a);
var a = 3;
// undefined

 

This is where something unexpected happenes for the first time and we getthe output as 'undefined' instead of '3'.

The above case happens because 'Javascript hoists just the declarations and avoids the initializations'.

 

When a variable is intitalize and declare say, 'var a = 3', JavaScript hoists only the declaration part and thus 'a=3' is not hoisted and therefore not added to the memory.

If we declare and initialize a variable, say var a = 3;, only the var a;portion (the declaration) is going to be hoisted. The a = 3; (the initialization) is not hoisted and therefore not added to memory.

As we know, when the variable is declared but not initialized, the variable is automatically initialized to 'undefined'. And, thus in the abpve example var a is set to 'undefined' and not '3'.

console.log(a);
var a = 3;
// undefined

 

In fact, the code is complied as:

var a;
console.log(a);
a = 3;
// undefined

 

Best Practice

 

Due of hoisting in javaScript, it is usually considered good practice to declare our variable always at the top of our respective scopes. Following this removed the risk of any undesirable effects in the code. declare your variables at the top of their respective scopes. This way there are no undesirable effects such as undefined variables in the code.

 

Thanks


About Author

Ishaan Madan

Ishaan, a skilled technical project manager, excels at breaking down complex projects into manageable tasks. With a background in both technology and project management, he offers a unique perspective to every project he undertakes. His effective communication skills enable him to collaborate seamlessly with both technical and non-technical stakeholders, ensuring everyone is aligned towards shared objectives. He has hands-on experience in utilizing agile methodologies like Scrum and Kanban to drive project management and foster team collaboration. He leverages project management tools such as JIRA, Trello, and Clickup to monitor progress, manage tasks, and facilitate communication among team members and stakeholders. Moreover, his proficiency in full-stack development empowers him to comprehend the technical aspects of projects and provide guidance to developers when necessary. He demonstrates expertise in utilizing popular Python frameworks like Django and Flask, along with data analysis and manipulation libraries such as NumPy and Pandas. On the front-end, Ishaan adeptly employs JavaScript libraries like React and Angular to craft visually appealing and user-friendly interfaces. Additionally, he possesses proficiency in HTML, CSS, and JavaScript for designing responsive and mobile-friendly layouts.

Request For Proposal

[contact-form-7 404 "Not Found"]

Ready to innovate ? Let's get in touch

Chat With Us