What is this problem in JavaScript's selfexecuting anonymous function?

Let's analyze this JavaScript code snippet that demonstrates a common confusion with variable hoisting and function declarations in self-executing anonymous functions.

var name = 'Zakir';
(() => {
    name = 'Rahul';
    return;
    console.log(name);
    function name(){
        let lastName = 'Singh';
    }
})();
console.log(name);

Naive Analysis (Incorrect)

At first glance, you might expect this sequence:

  1. Global variable name is set to 'Zakir'
  2. Inside the IIFE, name is reassigned to 'Rahul'
  3. Function returns early
  4. Global name should now be 'Rahul'

This would give us the wrong expectation:

Rahul

The Hoisting Reality

However, JavaScript's hoisting behavior changes everything. Function declarations are hoisted to the top of their scope, creating a local variable that shadows the global one.

Here's what actually happens during execution:

var name = 'Zakir';
(() => {
    // After hoisting, this is what JavaScript sees:
    function name(){
        let lastName = 'Singh';
    }
    name = 'Rahul';  // Assigns to LOCAL function, not global
    return;
    console.log(name);
})();
console.log(name);  // Global name is still 'Zakir'
Zakir

Key Points

  • The function name() declaration is hoisted to the top of the IIFE scope
  • This creates a local variable name that shadows the global name
  • The assignment name = 'Rahul' only affects the local variable
  • The global name remains unchanged as 'Zakir'

Comparison

Scenario Local Variable Created? Global Variable Affected? Output
With function declaration Yes (hoisted) No 'Zakir'
Without function declaration No Yes 'Rahul'

Conclusion

Function hoisting creates local scope that shadows global variables. Understanding hoisting is crucial for predicting JavaScript behavior, especially in self-executing functions where variable scope can be confusing.

Updated on: 2026-03-15T23:18:59+05:30

220 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements