5

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.

MD. Khairul Basar
  • 4,976
  • 14
  • 41
  • 59

1 Answers1

1

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]);
    }
})();
Black Mamba
  • 13,632
  • 6
  • 82
  • 105