16

there are two different ways to copy a array, using Array.concat or Array.slice,

for example:

var a = [1, 2, 3],

    c1 = [].concat(a),

    c2 = a.slice(0);

which way is better?

caiwf
  • 163
  • 1
  • 1
  • 5

2 Answers2

14

For clarity, you should use the method that is the documented method of taking a copy of an array (or portion thereof):

var c2 = a.slice(0);

On any decent browser the performance difference will be negligible, so clarity should be the deciding factor.

Alnitak
  • 334,560
  • 70
  • 407
  • 495
  • Documented where? – ericsoco Jan 19 '18 at 05:14
  • @ericsoco https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice - _"The `slice()` method returns a shallow copy of a portion of an array into a new array object selected from `begin` to `end` (`end` not included). The original array will not be modified."_ – Alnitak Jan 19 '18 at 08:19
5

In terms of performance, the difference between the two options are minimal, according to a jsperf.com test.

David Pärsson
  • 6,038
  • 2
  • 37
  • 52