Is this a genuine bug with variable naming? Code works fine otherwise


#1

A genuine conundrum. This is not exatly how I encountered this problem. I have re-written it to clarify. My original code was somewhat different, but still a valid, working code. The problem is the output isn't correct. Let me elaborate;

IMPORTANT: This is almost exactly the same as the Loops and Arrays II code, but was written in the next task, Conclusions. The only difference is the variable is called "name" instead of "names".

var name = ["Jess", "Steve", "Bob", "Chantelle", "Craig");

for (var i = 0; i < name.length; i++)
{
console.log("I know someone called " + name[i]);
}

Now, we know the code is supposed to ouput:

I know someone called Jess
I know someone called Steve
I know someone called Bob
etc.

The output I recieve from this code appears as:

I know someone called J
I know someone called e
I know someone called s
I know someone called s
I know someone called ,
I know someone called S
I know someone called t
etc.
ending with the g from Craig.

I was determind to make a code without assistance. After nearly going insane (or more than I already am), I stopped testing my memory, bit the bullet and went back to check the previous code for help. After declaring that it should indeed work, I copied the previous code exactly and it was fine. I then got the idea to change the variable name back to my original (from names to name) and it goes back to the wrong output. The site still reports the code as correct on submission either way.

If I change the variable name to anything but name, it works as intended. I was unable to find an answer via the forum or a web search (which actually had numerous working code examples of variables being called "name"). Any light that can be shed on this would be greatly appreciated.


#2

?? JS is the bestest language

There's a window.name property in your browser and assigning to it invokes a setter that ensures that the name refers to a string.

A warning or error would be nice, but nope.

https://developer.mozilla.org/en-US/docs/Web/API/Window/name
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/set


#3

Well, I still don't get it. My level of code comprehension isn't up to par, yet.

Would I be right in assuming that the use of "name" is in conflict with the window.name property and should never be used? I imagine there's likely a plethora of words assigned to functions that shouldn't be used.

Thank you for the reply. I look forward to the day I understand it :slightly_smiling:


#4

Yes, there's already something there and a setter function is triggered when you assign to that name. That function modifies the value you try to assign to it.

I don't know what best practices are, as far as I'm concerned JS in one big messy hack. You can tell if the name is there by typing it in your browser's JS console, if it's undefined then it should be all good I guess.