Can arrays in javascript be extended

Short Answer

Yes, arrays in JavaScript can be extended with other arrays without creating new arrays.

How can we extend arrays with other arrays without creating new arrays in javascript

Using the push function with spread (…) operator we can extend arrays in javascript. The code snippet for specific task is

arr2.push(...arr1);

let’s see the complete code

const arr1 = [6,3,"javascript"];
const arr2 = [4,3];

arr2.push(...arr1);
console.log(arr2);

The output of the program is

[4,3,6,3,"javascript"]

Explanation of the above code

First, let’s create two arrays and name them arr1 and arr2.
In line number 4 the spread operator expands the arr1 so the equivalent code will look like this

const arr1 = [6,3,"javascript"];
const arr2 = [4,3];

arr2.push(6,3,"javascript");
console.log(arr2);

Then it pushed all the elements at the end of the arr2. The elements will be pushed in the order as it is placed inside the push function.

Facebook
Twitter
LinkedIn
Pinterest

Leave a Reply

Your email address will not be published. Required fields are marked *

ABOUT ME !!
Johan William

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut elit tellus, luctus nec ullamcorper mattis, pulvinar dapibus leo.

RECENT POSTS

TEST