Last active
June 24, 2021 16:32
-
-
Save sayinserdar/03db6e850ff6f448d84f8514793bf69a to your computer and use it in GitHub Desktop.
Spread operator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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}) | |
} | |
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 ✌️
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
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?