Last active
July 1, 2021 09:16
-
-
Save Elijah-trillionz/7faa46818908188e849cf8416d6f3b48 to your computer and use it in GitHub Desktop.
Spread Operators with Arrays
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
// spread operators allows any iterable to be expanded | |
// it can serve as a means of adding arrays (concatenation) | |
const arr1 = [1, 3, 4] | |
const arr2 = [10, 13, 5] | |
const bothArr = [...arr1, ...arr2] | |
// you can use this to update an array with | |
// another array without leading to a multidimensional array | |
let arr1 = [1, 3, 4] | |
const arr2 = [10, 13, 5] | |
arr1 = [...arr1, ...arr2, "Hello"] | |
// changes to arr2 at this point will not affect arr1 | |
// it can as well be used to copy an array without referencing | |
const arr1 = [1, 3, 4] | |
const arr2 = [...arr1] | |
// arr2 is not referencing arr1 i.e changes to arr1 | |
// after line 16 will not affect arr2 and vice versa, but this is not the case below | |
const arr1 = [1, 3, 4] | |
const arr2 = [arr1] // or simply arr2 = arr1 | |
arr1.push(6) // will reflect in arr2 | |
arr2.push(3) // will reflecg in arr1 | |
// copying multidimensional arrays is not recommended with spread operators | |
// because spread operator goes one step level deep while copying array | |
const arr1 = [[1,2], [2,3], [3,4]] | |
const arr2 = [...arr1] | |
arr2.pop().pop() // will reflect on arr1 which isn't what we want | |
// make your corrections, suggestions, observations below |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment