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.

2

1 Answer 1

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]);
    }
})();

Sign up to request clarification or add additional context in comments.

4 Comments

Your explanation is wrong. window.name has nothing to do with html attributes
the IIFE is a more creative answer than "change the variable names."
@M.Davis No, window.name is about the browsing context (i.e. the browser window/tab) and has nothing to do with HTML. Of course, the IIFE is the correct solution.
@Bergi my bad, I was looking at the wrong link

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.