Skip to content

Instantly share code, notes, and snippets.

@sandrabosk
Created April 28, 2020 21:47
Show Gist options
  • Save sandrabosk/a2fc2f0b8afa235e9be9294c886f9ff5 to your computer and use it in GitHub Desktop.
Save sandrabosk/a2fc2f0b8afa235e9be9294c886f9ff5 to your computer and use it in GitHub Desktop.
// ************************************************
// ************** Spread operator *****************
// ************************************************
// Merging arrays
const reptiles = ['snake', 'lizard', 'alligator'];
const mammals = ['puppy', 'kitten', 'bunny'];
// ES5 approach:
const animals = [];
reptiles.forEach(oneReptile => animals.push(oneReptile));
mammals.forEach(oneMammal => animals.push(oneMammal));
console.log(animals); // [ 'snake', 'lizard', 'alligator', 'puppy', 'kitten', 'bunny' ]
// comment out the previous when demo the next:
// ES6 approach using spread operator:
const reptiles = ['snake', 'lizard', 'alligator'];
const mammals = ['puppy', 'kitten', 'bunny'];
const animals = [...mammals, ...reptiles];
console.log(animals); // [ 'puppy', 'kitten', 'bunny', 'snake', 'lizard', 'alligator' ]
// Copying arrays
// .slice()
const names = ['ana', 'milo', 'ivan'];
const names2 = names.slice();
console.log(names2); // => [ 'ana', 'milo', 'ivan' ]
// spread operator
const names = ['ana', 'milo', 'ivan'];
const names3 = [...names];
console.log(names3); // => [ 'ana', 'milo', 'ivan' ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment