Skip to content

Instantly share code, notes, and snippets.

@JulianG
Last active July 18, 2019 15:31
Show Gist options
  • Save JulianG/28dab4af6abb7ba24f29db1e4bfe32d1 to your computer and use it in GitHub Desktop.
Save JulianG/28dab4af6abb7ba24f29db1e4bfe32d1 to your computer and use it in GitHub Desktop.
spread vs slice

DON'T DO THIS!

When working on legacy projects it may be tempting to go around changing

const myCopy = arr.slice();

with:

const myCopy = [...arr];

but... DON'T DO IT!

It's not exactly the same.

Example:

const arr = [1,2,3];
arr[10] = 11; // (why would anyone do this is beyond me)

arr.forEach((n,i) => console.log(i,n))
// 0 1
// 1 2
// 2 3
// 10 11

arr.slice().forEach((n,i) => console.log(i,n))
// 0 1
// 1 2
// 2 3
// 10 11

[...arr].forEach((n,i) => console.log(i,n))
// 0 1
// 1 2
// 2 3
// 3 undefined
// 4 undefined
// 5 undefined
// 6 undefined
// 7 undefined
// 8 undefined
// 9 undefined
// 10 11
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment