DEV Community

Ayesha Ali
Ayesha Ali

Posted on

2

⚡Two Ways to Merge Arrays in JavaScript

Hi Everyone 👋
Image description

I am here to discuss with you Spread operator "..." And .Concat()
method in JavaScript.

⚡Here are 2 ways to combine your arrays and return a NEW array. I
like using the Spread operator, but if you need older Browser
support you can go through .Concat().

⚡Spread is fantastic when you know beforehand that you're dealing
with arrays. But what happens when the source is something else.

✍️Lets walk through an example,
const isArray = [1,2,3];
const notArray = 'random';

And we want this output : [1, 2, 3, 'random']

Here using spread operator the output comes
😱 [ 1, 2, 3, 'r', 'a', 'n', 'd', 'o', 'm' ]

And with .concat it works fantastic
✅ [ 1, 2, 3, 'random' ]

Note !!
So here's the quick rule. If you know you're dealing with arrays, use spread. But if you might be dealing with the possibility with a non-array, then use Concat to merge an array. 👍

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay