4

I am new to javascript and i have tried one example today, can someone help me to explain why?

all test are done on console panel from Chrome:

var greetingHello = "Hello";
var name = prompt("please enter your name");
document.write(greetingHello + " " + name + "<br>");

var name = new Array("name1","name2","name3");
document.write(name[0]);

The result is n

But if i change the second "name" variable from "name" to "myName", and executed myName[0]

the result is "name1"

Why is it so strange?

echo
  • 167
  • 1
  • 1
  • 12

1 Answers1

6

Your problem comes from the conflict with String window.name, when you try to set name in the global namespace, you're really invoking a setter which calls toString and ["name1","name2"].toString()[0] === "n".

This behaviour may differ across different browsers depending on the implementation of their var.

Paul S.
  • 64,864
  • 9
  • 122
  • 138
  • `name` is protected by `var`. There should be no conflict. – Frédéric Hamidi Mar 31 '14 at 15:05
  • 3
    @FrédéricHamidi try it in _Chrome_ – Paul S. Mar 31 '14 at 15:05
  • +1, successfully reproduced this using Opera 20. Also, `var myName = new Array("name1", "name2"); window.myName;` will print the array in the console. – UweB Mar 31 '14 at 15:07
  • @Paul, j08691's fiddle gives the expected result in Chrome. However, I suspect that's because the fiddle doesn't parse `var name = ...` in the global scope. I will double-check. – Frédéric Hamidi Mar 31 '14 at 15:08
  • @FrédéricHamidi it's wrapped in the _onload_, see http://jsfiddle.net/D54mG/ – Paul S. Mar 31 '14 at 15:09
  • Yup, I double-checked, and Chrome's behavior is indeed what you describe. Firefox still allocates a new `name` variable, even in the global scope. Now I wonder which one is right :) – Frédéric Hamidi Mar 31 '14 at 15:10
  • @FrédéricHamidi Consider `var document = document.implementation.createHTMLDocument();` and then tell me which one is right. – Paul S. Mar 31 '14 at 15:13
  • @Paul, if I had to decide (fortunately, I don't), I would say `var` should never be ignored for global names. It is always possible to omit `var` (or say `window.document`) if you want to do that. – Frédéric Hamidi Mar 31 '14 at 15:15
  • I can not fully understand what you are talking about, but one thing is sure that the problem is only existing on Chrome. I do not have problem with another browsers. Can someone make a conclusion at the end to help me understand it? Thanks a lot – echo Mar 31 '14 at 15:33
  • Thanks a lot for all of you :) – echo Mar 31 '14 at 15:44