Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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:
- Global variable
nameis set to 'Zakir' - Inside the IIFE,
nameis reassigned to 'Rahul' - Function returns early
- Global
nameshould 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
namethat shadows the globalname - The assignment
name = 'Rahul'only affects the local variable - The global
nameremains 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.
Advertisements
