Guest User

Untitled

a guest
May 25th, 2018
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.28 KB | None | 0 0
  1. Today I'll be diving into the Javascript Spread Operator (`...`), and its various use-cases.
  2.  
  3. The spread operator was released as part of ES6 (which was a major Javascript release a couple years back that introduced some awesome new JS syntax, functions, etc.). I recently came across it in a tutorial I was working through and didn't know what it was... you can learn along with me.
  4.  
  5. As mentioned in the post title, the spread operator is written as three periods: `...`
  6. It can be used, as the name suggests, to "spread" or expand the contents of an array or other iterable object into individual arguments. I had no idea what that really meant / how to apply it until I went through some examples, so here goes.
  7.  
  8. --------------------
  9.  
  10. **EX. 1: Combining Arrays**
  11. Let's start out with a simple example. We begin with an initial array:
  12. ```javascript
  13. let array1 = [1, 2, 3];
  14. ```
  15.  
  16. Now let's try to insert array1 into array2, below, and print the result. Note here we are NOT using the spread operator.
  17. ```javascript
  18. let array2 = [array1, 4, 5, 6];
  19. console.log(array2);
  20. // [[1, 2, 3], 4, 5, 6]
  21. ```
  22. As you can see above, `array1` is inserted into `array2` as an array *within* an array. But what if we want to extract the values from `array1` as individual arguments, so that we return one single array of individual values. We can use the spread operator to achieve this:
  23. ```javascript
  24. let array1 = [1, 2, 3];
  25. let array2 = [...array1, 4, 5, 6];
  26. console.log(array2);
  27. // [1, 2, 3, 4, 5, 6]
  28. ```
  29. --------------------
  30.  
  31. **EX. 2: Copying Arrays**
  32.  
  33. Here's a similar example, that I think is slightly more confusing/nuanced. Take an initial array:
  34. ```javascript
  35. let array1 = ["a", "b", "c"];
  36. ```
  37. What if we want to copy the contents of that array into a NEW array? Common sense might tell you that this is a fine solution:
  38. ```javascript
  39. let array2 = array1;
  40. ```
  41. Even after we print it out, it looks kosher:
  42. ```javascript
  43. console.log(array2);
  44. // ["a", "b", "c"]
  45. ```
  46. But hold up, what happens when we try to manipulate our new array, `array2`? I'll paste previous code below to illustrate this clearly:
  47. ```javascript
  48. let array1 = ["a", "b", "c"];
  49. let array2 = array1;
  50. array2.push("d") // we push a new value into array2
  51.  
  52. console.log(array2);
  53. // ["a", "b", "c", "d"]
  54. console.log(array1);
  55. // ["a", "b", "c", "d"]
  56. ```
  57. As you can see above, when we tried to manipulate `array2`, `array1` was also changed. We can use the spread operator to copy the contents of one array into another, and then manipulate the new array without affecting the original array. Like so:
  58. ```javascript
  59. let array1 = ["a", "b", "c"];
  60. let array2 = [...array1]; // we use the spread operator to copy the array
  61. array2.push("d") // we push a new value into array2
  62.  
  63. console.log(array2);
  64. // ["a", "b", "c", "d"]
  65. console.log(array1);
  66. // ["a", "b", "c"]
  67. ```
  68. --------------------
  69.  
  70. **EX. 3: Concatenating Arrays**
  71.  
  72. Another similar use-case, we can use the spread operator to concatenate arrays:
  73. ```javascript
  74. let array1 = [1, 2, 3];
  75. let array2 = [4, 5, 6];
  76. // using the JS concat function:
  77. let array3 = array1.concat(array2);
  78. console.log(array3);
  79. // [1, 2, 3, 4, 5, 6]
  80.  
  81. // using the spread operator:
  82. let array3 = [...array1, ...array2];
  83. console.log(array3);
  84. // [1, 2, 3, 4, 5, 6]
  85. ```
  86.  
  87. --------------------
  88.  
  89. **EX. 4: Printing Array Contents**
  90. Simple but powerful use case here -- Let's print the contents of an array using the spread operator.
  91. ```javascript
  92. array = ["cat", "dog", "fish"];
  93. console.log(array); // without spread operator
  94. // ["cat", "dog", "fish"]
  95. console.log(...array); // WITH spread operator
  96. // cat dog fish
  97. ```
  98. You can see that using the spread operator prints/returns the three array components separately, as opposed to printing the array itself.
  99.  
  100. --------------------
  101.  
  102. **EX. 5: Convert Individual Nodes / Arguments Into an Array**
  103.  
  104. Slightly different use case here... let's write a function that takes an arbitrary number of values as arguments, and creates an array out of them:
  105. ```javascript
  106. function argsToArray(...args) {
  107. console.log(args);
  108. };
  109.  
  110. argsToArray("left", "right", "up", "down"); // takes four individual strings as args
  111. // ["left", "right", "up", "down"]
  112. ```
  113.  
  114. Or even more fun, we can use the same kind of spread operator logic + some DOM querying to create an array of DOM elements
  115. ```javascript
  116. [...document.querySelectorAll('p')]; // returns an array of all <p> elements on a page
  117. ```
  118.  
  119.  
  120. --------------------
  121.  
  122. **EX. 6: Map Array Contents to Individual Function Args**
  123. Sort of the exact opposite of the previous example, here we'll use the spread operator to "spread" the contents of an existing array to individual input args in a function:
  124. ```javascript
  125. // define an array of numbers
  126. numsArray = [1, 2, 3, 4];
  127. // define a function that takes four separate arguments and prints their sum
  128. function addNums(a, b, c, d) {
  129. console.log(a + b + c + d);
  130. };
  131.  
  132. addNums(numsArray); // first we try to simply give the pre-defined number array as an argument
  133. // some undefined nonsense
  134.  
  135. addNums(numsArray[0], numsArray[1], numsArray[2], numsArray[3]]; // we could separate the values manually, but this sucks
  136. // 10
  137.  
  138. addNums(...numsArray); // or, we could just use the spread operator. Success!
  139. // 10
  140. ```
  141.  
  142. Those are just few applications to get the juices flowin'. There are plenty more, which I'll hopefully explore in different contexts in future posts.
  143.  
  144.  
  145. --
  146.  
  147. Thx for reading, love you guys,  
  148.  
  149. noah
Add Comment
Please, Sign In to add comment