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.