0

below are two different ways to use concat. nameage and nameage2 produce somewhat different results, which also seem to be described differently in different browsers.

var name = ["david","ibrahim","lagan"];
var age = [23, 34, 24];

var nameage = name.concat(age);
var nameage2 = [name].concat(age);

for example, in chrome: console.log(nameage); produces "david,ibrahim,lagan23,34,24", whereas console.log(nameage2); produces "["david,ibrahim,lagan", 23, 34, 24]"

Can someone explain what the difference is between these two approaches, and how it might impact use of concat? (Is one way more 'correct'?)

1 Answer 1

5

In the second one, you're putting the "name" array inside an array, as its first element, and then concatenating the "age" array onto that.

So:

[name]

gives you

[ [ "david", "ibrahim", "lagan" ] ]

It's an array inside of an array. When you concatenate onto that, you get

[ [ "david", "ibrahim", "lagan" ], 23, 34, 24 ]

It's not correct to think of the two samples you posted as two "approaches" — they're two quite different things. Which is "correct"? It depends on what result you want.

Sign up to request clarification or add additional context in comments.

6 Comments

that makes sense; also it's consistent with the way Firefox displays the results. Do you have any idea why, in Chrome, the comma is omitted between "lagan" and "23"? It seems like it should be 'all one array', thus including the comma.
Hmm .. Chrome isn't doing that for me when I console.log() those values. It shows the commas correctly.
for the first version (nameage)? interesting. it pulls the comma for me using both console.log() and document.write().
@GregoryTippett wow Chrome is indeed doing some really weird stuff. I'm confused.
@GregoryTippett ah - I think it has to do with using the variable name "name" in the global context. Try using "theName" instead of just "name". (The identifier "name" in the global context is special, as it has to do with the window's internal name? or something like that? I'm not sure.)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.