Created
September 22, 2022 14:53
-
-
Save jbollman7/5ed95557ccdd94f009b447c3b84ce180 to your computer and use it in GitHub Desktop.
Spread Rest Operator Example
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
/** | |
... either means spread operator OR Rest operator | |
Spread Operator -> Expand array or Object Literal | |
Rest Operator -> Function to get all the parameter ina function | |
Basically its rest operator if you see ... in the method signature | |
**/ | |
//Add the elements of an existing array into a new array | |
var array1 = ['a','b','c'] | |
var array2 = ['pizza', 'cat', ...array1]; | |
console.log(array2); | |
var array1 = ['a','b','c'] | |
var array2 = ['pizza', 'cat', array1]; | |
console.log(array2); | |
//the contents of the second snippet above is the array is nested within array 2, instead of just adding all the contnets of array1 inside of array2 | |
// pass elements of an array as arguments to a function | |
function addThreeNumbers(x,y,z) { | |
console.log(x+y+z) | |
} | |
var args = [0,1,2]; | |
addThreeNumbers(...args); | |
//output is 3. If you have MORE elements in your array than what the function calls for, | |
// the other elements will be ignored | |
//copy arrays | |
var arr = [1,2,3]; | |
var arr2 = [...arr]; // same thing as arr.slice(); | |
arr2.push(4); | |
console.log(arr); | |
console.log(arr2); | |
// We are not referencing the same object, so arr2 will have the 4 at the end and arr will not | |
// concatenate arrays | |
var arr1 = [0,1,2]; | |
var arr2 = [3,4,5]; | |
arr1.concat(arr2); | |
arr1 = [...arr1, ...arr2]; | |
//Concat and the spread operator do the EXACT same thing | |
// Advantage with the spread is you can add more elements to concatenate. the concat() method cannot take more than 1 arg | |
// REST: condense multiple elements into an array. Opposite of spread | |
//REST collects multiple elements and consenses to a single array | |
function sum(b,...a){ | |
console.log(b,a); | |
} | |
sum(5,6,7); | |
// output 5 [6, 7] | |
// Only the last parameter in a function defintion can be a rest parameter | |
// This will cause all remaining (user supplied) params to be placed in a JS array | |
//https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters | |
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment