logologo
  • AI Tools

    DB Query GeneratorMock InterviewResume BuilderLearning Path GeneratorCheatsheet GeneratorAgentic Prompt GeneratorCompany ResearchCover Letter Generator
  • XpertoAI
  • MVP Ready
  • Resources

    CertificationsTopicsExpertsCollectionsArticlesQuestionsVideosJobs
logologo

Elevate Your Coding with our comprehensive articles and niche collections.

Useful Links

  • Contact Us
  • Privacy Policy
  • Terms & Conditions
  • Refund & Cancellation
  • About Us

Resources

  • Xperto-AI
  • Certifications
  • Python
  • GenAI
  • Machine Learning

Interviews

  • DSA
  • System Design
  • Design Patterns
  • Frontend System Design
  • ReactJS

Procodebase © 2024. All rights reserved.

Level Up Your Skills with Xperto-AI

A multi-AI agent platform that helps you level up your development skills and ace your interview preparation to secure your dream job.

Launch Xperto-AI

Understanding Hoisting in Vanilla JavaScript

author
Generated by
Abhishek Goyan

22/10/2024

hoisting

Sign in to read full article

JavaScript is a versatile language and has its quirks, one of which is hoisting. If you've ever been confused about why a variable or function works before it has been declared, you’ve encountered this behavior. Today, we will dive deep into what hoisting is, how it works, and why it's important to understand, especially when prepping for your JavaScript interviews.

What is Hoisting?

Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their containing scope during the compile phase. Essentially, the interpreter scans through your code, looking for variables and function declarations, and hoists them to the top before executing the code.

This means that you can use variables and functions before they are declared in your code, which can sometimes lead to surprising results.

Variable Hoisting

Let’s start with variable hoisting. In JavaScript, when you declare a variable using var, that variable is hoisted to the top of its functional scope or global scope (if declared outside of any function). Here’s a simple example to illustrate this:

console.log(myVar); // undefined var myVar = 5; console.log(myVar); // 5

In the example above, the first console.log outputs undefined. Even though we attempt to log myVar before declaring it, JavaScript hoists the declaration (not the assignment) of myVar to the top. So, when logging myVar before the assignment, it exists but is implicitly set to undefined.

To clarify this further, the code above is interpreted like this by JavaScript:

var myVar; // Declaration is hoisted console.log(myVar); // undefined myVar = 5; // Assignment console.log(myVar); // 5

Function Hoisting

Hoisting applies to function declarations as well, which means you can call a function before its declaration without any problem. Here’s an example:

hello(); // "Hello, World!" function hello() { console.log("Hello, World!"); }

Here, the function hello is hoisted completely, allowing you to call it before its actual declaration in the code. The entire function definition is hoisted above the call.

However, it's essential to note that function expressions, especially those defined with const or let, behave differently:

console.log(greet); // undefined var greet = function() { console.log("Hi there!"); }; greet(); // TypeError: greet is not a function

In this case, the variable greet is hoisted so it exists before the assignment, but since its assignment is a function expression, the output of the first console.log(greet) remains undefined. When you try to call greet(), it results in an error since greet is not yet assigned to a function at that point.

Hoisting with let and const

Starting with ES6 (ECMAScript 2015), let and const introduced new ways to declare variables that behave differently concerning hoisting. When using these keywords, the variable is still hoisted to the top of the block scope, but it cannot be accessed until it has been declared, which leads to a "Temporal Dead Zone."

Here’s an example:

console.log(myVar); // ReferenceError: myVar is not defined let myVar = 10;

In this case, attempting to access myVar before its declaration leads to a ReferenceError. This behavior helps prevent common pitfalls associated with variable hoisting.

Common Misconceptions

  1. Hoisting is Not a Free Pass: Just because you can use a variable or function before it is declared doesn’t mean you should. It can lead to unreadable and confusing code.

  2. Only Declarations are Hoisted: It’s important to remember that only the declarations are hoisted—assignments are not. Therefore, it’s a good practice to declare variables at the top of their scope.

  3. Scoped vs. Global Hoisting: Hoisting works differently between global and local scopes. When variables are declared in functions, they are hoisted to the function’s top, while global variables are hoisted to the top of the script.

Understanding hoisting can significantly enhance your debugging skills and your ability to reason about code execution order. Knowing how hoisting works will also prepare you to answer questions confidently in interviews, where understanding JavaScript's behavior can significantly impact the outcomes of your coding challenges.

Popular Tags

hoistingjavascriptvanilla js

Share now!

Like & Bookmark!

Related Collections

  • JavaScript Mastery: From Basics to Advanced Techniques

    15/10/2024 | VanillaJS

  • JavaScript Coding Challenges for Interviews

    14/09/2024 | VanillaJS

  • JavaScript Interview Mastery: 20 Essential Concepts

    22/10/2024 | VanillaJS

Related Articles

  • Understanding JavaScript Closures

    22/10/2024 | VanillaJS

  • Mastering Arrays and Objects in Vanilla JavaScript

    15/10/2024 | VanillaJS

  • Mastering Control Structures in JavaScript

    15/10/2024 | VanillaJS

  • Memoization in JavaScript

    22/10/2024 | VanillaJS

  • Mastering Local Storage and Session Storage in Vanilla JavaScript

    15/10/2024 | VanillaJS

  • Understanding JavaScript Destructuring Assignment

    22/10/2024 | VanillaJS

  • Understanding Rest and Spread Operators in Vanilla JavaScript

    22/10/2024 | VanillaJS

Popular Category

  • Python
  • Generative AI
  • Machine Learning
  • ReactJS
  • System Design