DEV Community

Aman Kumar
Aman Kumar

Posted on

Dive into JavaScript's Hidden Layers: Nested Scopes & Hoisting πŸŒ€πŸ’‘

In the world of JavaScript, understanding how scope works is essential to writing clean, error-free code. When scopes nest inside each other, things get more interesting! 🌟 Today, we’re diving into Nested Scope and exploring Hoistingβ€”all with a fun, easy-to-follow guide.


🌳 Understanding Nested Scope 🌳

In JavaScript, when you define a function inside another function, it creates nested scopes. The inner function can access variables from its outer function, but the outer function can’t see inside the inner function.

Let’s look at an example:

function one() {
    const username = "Ayush";

    function two() {
        const website = "YouTube";
        console.log(username); // Output: Ayush
        // πŸ” Note: Function "two" can access the variables of function "one"
    }
    two();
    // console.log(website); // ❌ Error: Can't access "website" from function "two"
}

one();
Enter fullscreen mode Exit fullscreen mode
  • Here, the inner function two() can access username from the outer function one(). However, if you try to access website outside two(), it throws an error because it is scoped to two() only.

Nested Scope in Conditionals πŸ”„

if (true) {
    const username = "Ayush";
    if (username === "Ayush") { // true
        const website = "YouTube";
        console.log(username + website); // Output: Ayush YouTube
        // βœ… We can access "username" inside this block!
    }
    // console.log(website); // ❌ Error: Can't access "website" outside this block
}
// console.log(username); // ❌ Error: Can't access "username" outside the block
Enter fullscreen mode Exit fullscreen mode
  • Even in conditionals (if statements), block scope behaves similarly: variables declared inside one block {} can’t be accessed outside of it.

⚑ Hoisting: The Magic Trick of JavaScript! 🎩✨

Hoisting allows you to use functions and variables before you declare them in your code. However, the way JavaScript handles hoisting differs for functions and variables.

Function Hoisting πŸš€

In JavaScript, function declarations are fully hoisted. This means you can call a function before it's written in your code. Here's an example:

console.log(addOne(5)); // Output: 6

function addOne(num) {
    return num + 1;
}
Enter fullscreen mode Exit fullscreen mode
  • Even though the addOne function is defined after it’s called, the JavaScript engine "hoists" it to the top of the code, making it available for use.

Variable Hoisting with Functions ⚠️

Variables assigned with let, const, or function expressions (like arrow functions or anonymous functions) are not fully hoisted. You’ll get an error if you try to use them before they're defined:

// console.log(addTwo(5)); // ❌ Error: Cannot access 'addTwo' before initialization

const addTwo = function (num) {
    return num + 2;
};
Enter fullscreen mode Exit fullscreen mode
  • Unlike function declarations, function expressions (when a function is assigned to a variable) don’t get fully hoisted. They behave like any other variable declaration.

πŸš€ Key Takeaways:

  1. Nested Scope: Inner functions can access variables from their parent scope, but not vice versa.
  2. Block Scope: Variables declared inside {} can’t be accessed outside.
  3. Hoisting: Function declarations are hoisted, but function expressions are not.

By mastering scope and hoisting, you’ll gain a deeper understanding of how JavaScript works under the hood. Now, go ahead and put this knowledge into practice! πŸ’ͺπŸ”₯

Top comments (0)