anni
anni

Reputation: 288

Unexpected behavior shown by the function concat and push

I was testing my code in goolge console and I found that concat() is not working as I have illustrated below:

var a = ["a"]; //undefined
a.concat("b","c"); // ["a","b","c"] 

Now when I push some other string then that string replaces the indexes of "b" and "c"

that is[continued]

 a.push("e","f"); // 3 
 a // ["a", "e","f"]

Did you notice 3 in the line where the string is pushed. It is interesting to me that at first we contact "b" and "c" and then, when I try to get value of say 1 index then it return undefined! and then, when we push "e" and "f" in the same array then these string replaces the indexes of concated string. Now the question is:

1) Why do these concat and push function show strange behavior?

2) Do this mean the failure of cancat function?

3) Is thiscontact function is just for nominal?

Upvotes: 0

Views: 112

Answers (1)

Montagist
Montagist

Reputation: 401

This is correct. Concat isn't modifying the array like you expect it to.

When you:

a.concat("b","c");

It returns an array of ["a","b","c"], but you aren't saving the reference (which you would do like this)

a = a.concat("b","c");

Some info from the MDN:

concat does not alter this or any of the arrays provided as arguments but instead returns a shallow copy that contains copies of the same elements combined from the original arrays.

Upvotes: 3

Related Questions