Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
81
rated 0 times [  86] [ 5]  / answers: 1 / hits: 75830  / 6 Years ago, mon, february 19, 2018, 12:00:00

What is the difference between spread operator and array.concat()




let parts = ['four', 'five'];
let numbers = ['one', 'two', 'three'];
console.log([...numbers, ...parts]);




Array.concat() function




let parts = ['four', 'five'];
let numbers = ['one', 'two', 'three'];
console.log(numbers.concat(parts));





Both results are same. So, what kind of scenarios we want to use them? And which one is best for performance?



More From » arrays

 Answers
90

Well console.log(['one', 'two', 'three', 'four', 'five']) has the same result as well, so why use either here? :P



In general you would use concat when you have two (or more) arrays from arbitrary sources, and you would use the spread syntax in the array literal if the additional elements that are always part of the array are known before. So if you would have an array literal with concat in your code, just go for spread syntax, and just use concat otherwise:



[...a, ...b] // bad :-(
a.concat(b) // good :-)

[x, y].concat(a) // bad :-(
[x, y, ...a] // good :-)


Also the two alternatives behave quite differently when dealing with non-array values.


[#55111] Thursday, February 15, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
miranda

Total Points: 655
Total Questions: 110
Total Answers: 121

Location: Netherlands
Member since Thu, Jul 1, 2021
3 Years ago
miranda questions
Sun, Jun 6, 21, 00:00, 3 Years ago
Tue, Mar 16, 21, 00:00, 3 Years ago
Sun, Feb 7, 21, 00:00, 3 Years ago
Mon, Jan 18, 21, 00:00, 3 Years ago
Fri, Jul 17, 20, 00:00, 4 Years ago
;