Strange behavior for variable "name" in javascript

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

all tests run on the console 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]);

Result n

But if I change the second variable "name" from "name" to "myName" and execute myName [0]

the result is "name1"

Why is this so strange?

+4
source share
1 answer

Your problem is due to a conflict with String window.name, when you try to install namein the global namespace, you really call the installer, which calls toString and ["name1","name2"].toString()[0] === "n".

var.

+6

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


All Articles