concat() Method in JavaScript

JavaScript1 min read
concat() Method in JavaScript
javascriptconcat method in javascriptarray methods

concat() is a built-in method in JavaScript that is used to merge two or more arrays together and return a new array with the combined elements.

concat() Method in JavaScript

  • concat() is a built-in method in JavaScript that is used to merge two or more arrays together and return a new array with the combined elements.
  • It doesn't modify the original array.

Example:

  • Let's create two arrays: form1 and form2.
let form1 = ['firstName', 'lastName']; let form2 = ['phoneNumber', 'email'];

To merge these arrays, use the concat() method:

let formData = form1.concat(form2); document.write("Form Data: " + formData.join(", ") + "<br>"); // Output: Form Data: firstName, lastName, phoneNumber, email

The formData array contains the elements of both form1 and form2.

  • Now, let's create two variables: salary and department.
let salary = 50000; let department = 'finance';

To merge these variables with formData, use the concat() method again:

let newFormData = formData.concat(salary, department); newFormData.forEach(item => { document.write(item + "<br>"); }); // Output: firstName lastName phoneNumber email 50000 finance

The newFormData array contains all elements of formData along with salary and department.

  • Using the concat() method, we can merge arrays and individual elements to create a new array.