Ad Code

Responsive Advertisement

Shadowing | Global naming pollution | IIFE

Shadowing : 

If we declare a variable in a certain scope with some name on its outer scope and if re-assign the value in inner scope the value will replaced or shadowed, it is known as shadowing. for example.

function hello(){
            var a = 10;
            if(1==1){
                var a = 23;
                alert("inner a = "+a);      // display 23, a is replaced by 23
            }
            alert("outer a = "+a);          // here also display 23
        }
        hello();

similarly, if we declare a function having some name and later on if we declare variable same as that function name then that become now a variable not a function. for example

function hello(){       // hello is a funtion here.
            console.log(10);  
        }

        var hello = "Now hello is no longer a function";
        hello();        // hello is now variable, 
                        // it throws an TypeError: hello is not a funtion

Illegal Shadowing : 

suppose a variable is declared using let keyword and try to re-declare using var keyword then this is called illegal shadowing.

function hello(){
            let a = 10;
            if(1==1){
                var a = 23;    
                alert("inner a = "+a);
            }
            alert("outer a = "+a);
        }
        hello();

output : Uncaught SyntaxError: Identifier 'a' has already been declared

These problems are called naming problem. To solve this problem we have IIFE (Immediately invoked function expression. 

IIFE : 

The function which invoked immediately while declaring it is known as IIFE. IIFE is an anonymous function which do not require the function name while declaring. Let's understand with an example.

(function(){
            console.log("this is iife");
        })();

IIFE does not create any global naming issue because it does not have a name.

Post a Comment

0 Comments