Hoisting in Javascript

Hoisting in Javascript

Unveiling JavaScript's Hoisting: Variable Declarations at the Forefront

Introduction

Javascript is a high level programming language used to build client-side and server-side that allows you to make web pages interactive. It is one of the three core technologies of World Wide Web content production.

This was one of my interview questions and one of the most important javascript topics to know about.

What is hoisting?

Before coming to hoisting let us briefly understand how vairables are declared in javascript, there are ways

  • var keyword: Variables declared by var are available throughout the function in which they're declared

  • let keyword: Variables declared by let are only available inside the block where they're defined

  • const keyword: Variables declared by const can only be given a value once and can not be changed later.

In JavaScript, variable declarations are conceptually moved to the top of their containing scope during the compilation phase, a behavior known as hoisting. This means that even though you may declare a variable later in your code, it behaves as if it were declared at the top of its scope. This can lead to scenarios where variables are accessed before they are actually declared, resulting in unexpected behavior such as returning undefined instead of throwing an error.

Consider the following example:

console.log(name); //prints undefined 
let name = "Aaron"; 
console.log(name); //prints Aaron

At first glance, one might expect this code to throw a ReferenceError because name is accessed before it's declared. However, due to hoisting, the code is interpreted differently by JavaScript.

During compilation, JavaScript moves the declaration of name to the top of its scope, resulting in the following equivalent interpretation:

let name; //declared first
console.log(name); //prints undefined 
name = "Aaron";
console.log(name); //prints Aaron

Conclusion

Understanding hoisting is crucial for JavaScript developers, as it can impact the behavior and predictability of their code. Being aware of how hoisting works allows developers to write cleaner and more efficient code, avoiding potential pitfalls and bugs.

Note: for any corrections do reach out to me using my socials present in the navbar.