Defining an array in javascript and storing the array name as a name

By executing the below code in javascript:

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

For me, it should output:

 Hello Pankaj Hello Kumar 

But javascript 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 the array as names , then it will exit as expected:

 Hello Pankaj Hello Kumar 

the name is not a javascript reserved keyword.

Could you tell me the reason for this behavior.

+5
source share
1 answer

This question has it all

The name is already attached to the window where you are located as window.name , so do not use it or use IIFE as shown below to avoid pollution of the global namespace

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

Source: https://habr.com/ru/post/1272435/


All Articles