DEV Community

Akande Olalekan Toheeb for AWS Community Builders

Posted on • Edited on

Do you know what the concat() is used for?

Hi folks ๐Ÿ‘‹!

Trust you are well. I'm here again to show you an easy way of adding arrays.

I am Akande Olalekan Toheeb, a Nigerian self-taught developer who is passionate about solving problems and helping others with the easiest way in problem solving.

overview

Every beginner is exposed to the concatenation + when it comes to adding variables, arrays and even strings in JavaScript. Such that when you want to add an array to a predefined array, you do it this way:


 var array1= ["Akande", 22];
 var array2 = ["Olalekan", 25];

 array1 += array2;

console.log(array1);

Enter fullscreen mode Exit fullscreen mode

The console looks like this:

Image description

Every beginner are exposed to this because that's what they learn.

Here I provide you with a very easy way to do this.

The concat() is a method of adding arrays.

Let me show how it is done.

Suppose you want to add an array array_2 to another array array_1. All you need to is add .concat() to the first array and input the array you wish to add, array_2 inside the bracket.

This way :


var myConcat = (arr1, arr2) => arr1.concat(arr2);
console.log(myConcat(["Akande", 22], ["Olalekan", 25]));

Enter fullscreen mode Exit fullscreen mode

This prints ['Akande', 22, 'Olalekan', 25] to the console:

Image description

Using this method will save a lot of time and energy. Make use of it for best practice.

Thank you for reading, have a nice day!

Your appreciation is my motivation ๐Ÿ˜Š - Give it a like

Follow me on Twitter.
Click here to connect on Linkedln.

Top comments (0)