Hendrik Hendrik - 3 months ago 8
Javascript Question

Using name inside a Array yields different results in Firefox

I would like a little guidance here. Using JS Bin for this.
The whole issue here is : "name" when used as a VAR and inside an array:
---the console.log prints each letter:

var word = "Hi";
var name = ["John","Suzette","Mari-Louise","Tinus","Hendrik","Koos","Elna","Elbie"];
// Greeting
greeter(word,name);

function greeter(str,arr){
var counter;
for(counter = 0;
counter < arr.length;
counter++) {
console.log(str + " " + arr[counter]);
}
}


Output

"Hi J"
"Hi o"
"Hi h"
"Hi n"
"Hi ,"
"Hi S"
"Hi u"


However, changing the VAR to userName, yields the correct result,..I cant find any reference to 'name' being a reserved word in JS, so if someone could clarify this for me, it will be smashing.

var word = "Hi";
var userName = ["John","Suzette","Mari-Louise","Tinus","Hendrik","Koos","Elna","Elbie"];
// Greeting
greeter(word,userName);

function greeter(str,arr){
var counter;
for(counter = 0;
counter < arr.length;
counter++) {
console.log(str + " " + arr[counter]);
}
}


Result**

"Hi John"
"Hi Suzette"
"Hi Mari-Louise"
"Hi Tinus"
"Hi Hendrik"
"Hi Koos"
"Hi Elna"
"Hi Elbie"

Answer

If you debug, you will notice that name is already defined by the time you execute your code. It happens because global window context has name property which is string.
When you try to set ["a", "b", "c"] to this property, a browser converts it to a string, and it becomes "a,b,c". That's why when you iterate through it, you get characters.

console.log(name); // it already exists

var name = ["a", "b", "c"]; // assigns window.name property, becomes a string
var nameqwe = ["a", "b", "c"]; // creates local variable

console.log(name);
console.log(nameqwe);