Nicholas Tibbs
Nicholas Tibbs

Reputation: 170

Weird thing happens with array

I'm playing around on codepen.io but for some reason my code is not working as expected:

var name = ["one",'two','three'];
$('body').append('<p>'+ name[0] + '</p>');

That code is appending the letter "o" to the page. When I switch the code to:

var person = ["one",'two','three'];
$('body').append('<p>'+ person[0] + '</p>');

"one" is appended to the page. Anybody know what's going on?

Here is the example: http://codepen.io/ntibbs/pen/ZbPPBm

Upvotes: 3

Views: 44

Answers (1)

James Thorpe
James Thorpe

Reputation: 32222

You appear to be in the global scope, so when you declare your name variable, you're clashing with the global window.name property.

This property has to be a string, so whenever you assign anything to it, it is coerced to a string.

When ["one",'two','three'] is coerced to a string, it first performs an Array.join, and you end up with "one,two,three", which is assigned to name. name[0] gives you the first character of that, "o".

Using the different variable name, person, you don't see this issue because you're not fighting the window property.

Upvotes: 6

Related Questions