Last active
July 10, 2019 06:03
-
-
Save deleteman/a0fdd48202f931516e11c10d784a018e to your computer and use it in GitHub Desktop.
Simple examples for the spread operator
This file contains hidden or 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
let myArray1 = [1,2,3] | |
let myString = "Hey planet!" | |
let myObject = { | |
name: "Fernando Doglio", | |
age: 35, | |
country: "Uruguay", | |
[Symbol.iterator]: function* () { //we're making the object iterable so we can spread it | |
yield myObject.name | |
yield myObject.age | |
yield myObject.country | |
} | |
} | |
function test() { | |
console.log(arguments) | |
} | |
let splitLetters = [...myString] //no longer need for myString.split() | |
console.log(splitLetters) | |
//[ 'H', 'e', 'y', ' ', 'p', 'l', 'a', 'n', 'e', 't', '!' ] | |
let objLetters = {...myString} | |
console.log(objLetters) | |
/* | |
{ '0': 'H', | |
'1': 'e', | |
'2': 'y', | |
'3': ' ', | |
'4': 'p', | |
'5': 'l', | |
'6': 'a', | |
'7': 'n', | |
'8': 'e', | |
'9': 't', | |
'10': '!' } | |
*/ | |
test(...myString) | |
/* | |
[Arguments] { | |
'0': 'H', | |
'1': 'e', | |
'2': 'y', | |
'3': ' ', | |
'4': 'p', | |
'5': 'l', | |
'6': 'a', | |
'7': 'n', | |
'8': 'e', | |
'9': 't', | |
'10': '!' } | |
*/ | |
//the same thing | |
test.call(null, ...myArray1) | |
//[Arguments] { '0': 1, '1': 2, '2': 3 } | |
test.apply(null, myArray1) | |
//[Arguments] { '0': 1, '1': 2, '2': 3 } | |
let objValues = [...myObject] //if your object is iterable, this can substitute Object.values(myObject) | |
console.log(objValues) | |
//[ 'Fernando Doglio', 35, 'Uruguay' ] | |
let {name, age} = {...myObject} //spread properties into individual variables | |
console.log("Name::", name, " age::", age) | |
//Name:: Fernando Doglio age:: 35 | |
test(...myObject) //we've turned our object into 3 different arguments | |
//[Arguments] { '0': 'Fernando Doglio', '1': 35, '2': 'Uruguay' } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment