Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining array in javascript and keeping the name of array as name [duplicate]

While executing the below code in javascript:

var name=["Pankaj","Kumar"] ;

    for( var i=0;i<name.length;i++)
    {
        console.log("Hello "+name[i]);
    }

According to me ,it should output :

Hello Pankaj   
Hello Kumar

But javascript engine outputs :

Hello P  
Hello a  
Hello n  
Hello k  
Hello a  
Hello j  
Hello ,  
Hello K  
Hello u  
Hello m  
Hello a  
Hello r  

If we change the name of array as names ,then it outputs according to expectations:

Hello Pankaj  
Hello Kumar  

name is not a javascript reserved keyword .

Could you please let me know the reason for this behavior.

like image 587
Pankaj Chibhrani Avatar asked Nov 07 '22 15:11

Pankaj Chibhrani


1 Answers

This question has it all

Name is already attached to the window you're in as window.name so avoid using it or use IIFE as below to avoid polluting global namespace

(function(){
  var name=["Pankaj","Kumar"] ;

    for( var i=0;i<name.length;i++)
    {
        console.log("Hello "+name[i]);
    }
})();
like image 60
Black Mamba Avatar answered Nov 14 '22 22:11

Black Mamba