Skip to content

Instantly share code, notes, and snippets.

@sayinserdar
Last active June 24, 2021 16:32
Show Gist options
  • Save sayinserdar/03db6e850ff6f448d84f8514793bf69a to your computer and use it in GitHub Desktop.
Save sayinserdar/03db6e850ff6f448d84f8514793bf69a to your computer and use it in GitHub Desktop.
Spread operator
// Can be used instead of Array functions
const a = [1,2,4];
const b = [3,7,6];
const c = 1;
// a.concat(b);
let arr = [...a,...b];
// Unshift, push
// The difference is spread operator creates a new reference unlike the array functions.
arr = [...a,1]; // arr = a.push(1);
arr = [1,...a]; // arr = a.unshift(1);
// Accessing properties from a complex object
let seinfeldRocksBigBangSux =
{
'name': 'Jerry',
'surname': 'Seinfeld'
'bestFriends': ['George Costanza','Elaine Benes','Cosmo Kramer'],
'location': 'NYC'
}
// Clean syntax
const {name, surname, ...remainingProperties} = seinfeldRocksBigBangSux;
// Here's relatively complicated example.
const params =
{
...prevData,
name: externalData.name,
...(hobbies && {hobbies})
}
@elafari
Copy link

elafari commented Jun 23, 2021

When I run const params = {...(hobbies && {hobbies})} in the browser console of the latest chrome version I get: Uncaught ReferenceError: hobbies is not defined. Any idea?

@sayinserdar
Copy link
Author

const apiCall = function(hobbies,externalData) {const prevData = {ex: 1}; return {...prevData,name: externalData.name,...(hobbies && {hobbies})}}

apiCall(null,{name:123});
apiCall(123,{name:123});

To be less verbose I focused on hobbies. You can try running these. You'll see the difference ✌️

@elafari
Copy link

elafari commented Jun 24, 2021

In my case the hobbies variable has never been initialized, therefore the ReferenceError. When you wrap that in a function the reference automatically gets created for you. I guess it's not what I was expecting, but thanks anyway

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment