javascript - Why does an array with a variable name of 'names' turn into a string when i put in 'name'? -
i declared array called names. used while loop go on each name , log them console. then, accidentally mistyped 'names' 'name'. normally, gives out reference error, logged different characters of first name. , checked developer tools , looked variable "name" because did not define variable **"name"
var names = ['john', 'jane', 'mary', 'mark', 'bob']; var = 0; while (i < names.length) { console.log(name[i]); i++; }
what printed out in console
j o h n ,
then looked variable "name" cos did not declare , came out
names "john,jane,mary,mark,bob"
what reason behind this?
first of added simple console.log()
see name
is. in case did not define variable name
, default shorthand variable window.name
. explains behaviour, there no reference error
. lets take closer it:
var names = ['john', 'jane', 'mary', 'mark', 'bob']; var = 0; console.log(name); var charactersthatwillbeshown = name.substr(0, names.length); console.log(charactersthatwillbeshown); var loggedcharacters = ""; while (i < names.length) { loggedcharacters += name[i]; console.log(name[i]); i++; } console.log(loggedcharacters); console.log(charactersthatwillbeshown == loggedcharacters);
.as-console-wrapper { min-height: 100%; }
Comments
Post a Comment