JavaScript array behaves strangely when variable is called 'name'

I’m having a weird issue with JavaScript arrays. When I create an array and call it name, the loop doesn’t work as expected.

Here’s my code:

var name = ["Sarah", "Johnson"];

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

I expect this output:

Hi Sarah
Hi Johnson

But instead I get:

Hi S
Hi a
Hi r
Hi a
Hi h
Hi ,
Hi J
Hi o
Hi h
Hi n
Hi s
Hi o
Hi n

When I rename the array to names, everything works fine. I know name isn’t a reserved word in JavaScript. What’s causing this strange behavior?

This happens because name is a predefined property of the window object. When you declare var name, it gets coerced to a string automatically since window.name must always be a string. Your array ["Sarah", "Johnson"] gets converted to “Sarah,Johnson”, which is why you’re iterating over individual characters including the comma. I ran into this same issue years ago and it took me forever to figure out. The solution is exactly what you discovered - use a different variable name like names or userNames. You can verify this by checking typeof name after assignment - it’ll show “string” instead of “object”.

totally get why this is happening! name is a global property and messes with your array. renaming it to names is the way to go. just be careful with those common names in js!

This caught me off guard too when I first ran into it. The issue is window.name - it’s a built-in browser property that only stores strings for cross-window communication. When you declare var name globally, you’re overwriting this property. Since window.name can only hold strings, JavaScript converts your array to “Sarah,Johnson”. That’s why your loop goes through each character instead of array elements. I spent hours debugging this exact problem before figuring out the variable name was causing it. Always check if your variables conflict with global properties.