Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

JavaScript concat() method

The concat() method in JavaScript is used to merge two or more arrays together to create a new array. This method does not modify the original arrays, but instead creates a new array that contains the elements of the original arrays.

The concat() method takes any number of arguments, which can be either arrays or individual values. If an argument is an array, the elements of that array are added to the new array. If an argument is not an array, it is added to the new array as a separate element.

Here are some examples of how to use the concat() method:

const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const arr3 = [7, 8, 9];

// Concatenate two arrays
const newArray1 = arr1.concat(arr2);  // newArray1 is [1, 2, 3, 4, 5, 6]

// Concatenate three arrays
const newArray2 = arr1.concat(arr2, arr3);  // newArray2 is [1, 2, 3, 4, 5, 6, 7, 8, 9]

// Concatenate an array and individual values
const newArray3 = arr1.concat(4, 5, 6);  // newArray3 is [1, 2, 3, 4, 5, 6]

Note that if you pass an array-like object (such as a NodeList or a String) as an argument to the concat() method, it will be converted to an array before being added to the new array.

Here is an example of using the concat() method with an array-like object:

const elements = document.querySelectorAll('div');
const arr = [1, 2, 3];
const newArray = arr.concat(elements);  // newArray is [1, 2, 3, div, div, div]

The concat() method is often used to merge multiple arrays into a single array, or to add new elements to an existing array. It is a convenient way to create a new array without modifying the original arrays.

You can find the complete JavaScript Tutorials here.

Follow us on Facebook, YouTube, Instagram, and Twitter for more exciting content and the latest updates.

The post JavaScript concat() method appeared first on CodingTute.



This post first appeared on CodingTute, please read the originial post: here

Share the post

JavaScript concat() method

×

Subscribe to Codingtute

Get updates delivered right to your inbox!

Thank you for your subscription

×