JavaScript Glossary - Lesson #7

JavaScript Array .concat() Method

The Array concat method combines two or more values into a new array.

javascript
const newArray = oneArray.concat(secondArray);
javascript
// we have 2 arrays of people
const people = ['chris', 'nick'];
const newPeople = ['kap', 'william'];

// add them together to create a new array
const allPeople = people.concat(newPeople);

console.log(allPeople);
// output: ['chris', 'nick', 'kap', 'william']

Note: concat() creates a new array. It does not change the original array. To change the original array, look at Array push().

javascript
const newArray = firstArray.concat(secondArray);

// multiple parameters
const newestArray = firstArray.concat(secondArray, thirdArray, fourthArray);

// adding more than arrays
const newNewArray = firstArray.concat('a message', 50, ['stuff', 'stuff']);

This method can take several parameters. Each parameter will be added to the first array.

thingsToAdd (any type of value)

Values to be joined to the parent array. This can be an array of elements or values passed as arguments.

The method will return an array containing all the elements from the parent array and the value specified as arguments. If no arguments are provided, it will return an array containing the elements in the parent array.

js
// create an array
const names = ['John', 'Peter', 'James', 'Pammy'];
const moreNames = names.concat(['Rich', 'Matt']);

console.log(moreNames);
// output: Array ['John', 'Peter', 'James', 'Pammy', 'Rich', 'Matt']

Joining values or arrays to a given array. e.g Adding values to an array without mutating the parent array.

js
const months = ['March', 'April', 'May'];
const otherMonths = ['June', 'July'];

// combine the months to a new array
const totalMonths = months.concat(otherMonths);

console.log(totalMonths);
// output: Array ['March', 'April', 'May', 'June', 'July']

Want to improve your coding and design skills?

I'm continually researching the best practices and tools for coding.
Join 50,000+ developers looking to make cool stuff.

We value your privacy. 1-click unsubscribe.

Chris Sev

Chris Sev

Chris Sev is the co-founder of Better Dev. Coding better every day. Previously he created Scotch.io which was acquired.

Comments

What did you think of the article? Let us know!
(these comments are powered by GitHub issues and use 0 trackers)