Push an array into the same array JS

Topics related to client-side programming language.
Post questions and answers about JavaScript, Ajax, or jQuery codes and scripts.
Marius
Posts:107

Push an array into the same array JS

I'm trying to push an array into the same array in javascript, But it doesn't seem to be working; the third element is added continuously.
Here is my code so far:

Code: Select all

var arr = ['Hello', 'World!']
arr.push(arr);
console.log(arr);
Expected output: ['Hello', 'World!', ['Hello', 'World!']]

Does somebody know why my code doesn't work, and how to fix it?

Admin Posts:805
You are trying to push the same reference to the array. So, when the array updated later, the array inside the element will be updated as well.
To fix this, you need to push a copy of the array (another reference).
See the sample below.

Code: Select all

var arr = ['Hello', 'World!']
arr.push([...arr]);
console.log(arr);