Hey There 👋
Welcome to Episode 4 of my Array Methods Explain Show.
as always, if you are here then i suppose you must have pre knowledge of javascript and arrays.
we will be discussing only one method on this episode which is : CONCAT
The method concat creates a new array that includes values from other arrays and additional items.
the syntax of concat method is :
- item1, item2, item3, .... itemN : the arrays / elements to add.
It returns new array containing the extracted elements, and the original array remains same.
Now, lets look at examples :
- concatenating two arrays
let colors = ["Red", "Blue"];
let numbers = [1,2,3];
const colorNumber = colors.concat(numbers);
console.log(colorNumber); // ["Red", "Blue", 1, 2, 3]
- concatenating three arrays
let colors = ["Red", "Blue"];
let numbers = [1,2,3];
let veggie = ["Potato", "Carrot", "Raddish"];
const colorNumberVeggie = colors.concat(numbers, veggie);
console.log(colorNumberVeggie); // ["Red", "Blue", 1, 2, 3, "Potato", "Carrot", "Raddish"]
- concatenating nested arrays
let numbers1 = [1, [2,3]];
let numbers2 = [[4,5], [6,7]];
const numbers = numbers1.concat(numbers2);
console.log(numbers); // [1, [2, 3], [4, 5], [6, 7]]
- concatenating arrays and values
let colors = ["Red", "Blue"];
const moreColors = colors.concat("Yellow", ["White", "Black"]);
console.log(moreColors); // ["Red", "Blue", "Yellow", "White", "Black"]
BEHIND THE SCENES
The concat method does not alter the given array or any of the arrays provided as arguments but instead returns a copy that contains copies of the same elements combined from the original arrays. Elements of the original arrays are copied into the new array as follows:
- For objects concat copies object references into the new array. Both the original and new array refer to the same object. That is, if a referenced object is modified, the changes are visible to both the new and original arrays. This includes elements of array arguments that are also arrays.
- For data types such as strings, numbers and booleans (not String, Number and Boolean objects): concat copies the values of strings and numbers into the new array.
Top comments (0)