<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: Robert Aguilera</title>
    <description>The latest articles on Forem by Robert Aguilera (@robaguilera).</description>
    <link>https://forem.com/robaguilera</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F95804%2F1fb46f1a-6863-4fd7-a6ef-1d3ee70cb3aa.jpeg</url>
      <title>Forem: Robert Aguilera</title>
      <link>https://forem.com/robaguilera</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/robaguilera"/>
    <language>en</language>
    <item>
      <title>Spread Operator Tricks</title>
      <dc:creator>Robert Aguilera</dc:creator>
      <pubDate>Mon, 03 Sep 2018 23:11:43 +0000</pubDate>
      <link>https://forem.com/robaguilera/spread-operator-tricks-4g9k</link>
      <guid>https://forem.com/robaguilera/spread-operator-tricks-4g9k</guid>
      <description>

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--i47fieXm--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://thepracticaldev.s3.amazonaws.com/i/s5reg6x0xifp2qenwvqb.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--i47fieXm--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://thepracticaldev.s3.amazonaws.com/i/s5reg6x0xifp2qenwvqb.jpg" alt="I'm going to butter your bread"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;I recently came across some handy patterns using the spread operator so I thought I’d write up a quick blog post sharing some.&lt;/p&gt;

&lt;p&gt;For this blog post, I’m not going to cover the basics of the syntax. If you need a refresher, the &lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax"&gt;MDN docs&lt;/a&gt; are a great resource.&lt;/p&gt;

&lt;h3&gt;Immutability&lt;/h3&gt;

&lt;p&gt;Javascript has this lovely thing it does with objects. Whenever you attempt to make a copy of an object you might inadvertently make a reference to it instead.&lt;/p&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let oldNed = {
  name: 'Ned Stark',
  job: 'Warden of the North'
};
let newNed = oldNed;
newNed.job = 'Dead';
// oldNed variable is also mutated
console.log(oldNed) // { name: 'Ned Start', job: 'Dead' }
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Mutating data can lead to some hard to find bugs, so it’s worth the time and effort to ensure that you prevent this by properly copying any data that you need to change. One way is through the use of the spread operator.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;let newNed = {...oldNed};&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Any changes to newNed will not mutate the oldNed variable. However, there is one exception. The spread operator does not preform a deep clone of a nested object.&lt;/p&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let oldNed = {
  name: 'Ned Stark',
  job: 'Warden of the North',
  kids: ['John', 'Rob', 'Bran', 'Sansa', 'Arya', 'Rickon']
};
let newNed = { ...oldNed };
newNed.kids.splice(5)
// oldNed is now also missing Rickon :(
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;To get around this you have to also spread out the nested array&lt;/p&gt;

&lt;p&gt;&lt;code&gt;let newNed = { ...oldNed, kids: [...oldNed.kids] };&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Keep in mind that if you have a deeply nested object you might want to reach for some kind of custom function or library to help you with deep cloning.&lt;/p&gt;




&lt;p&gt;Here’s some other nifty immutable tricks.&lt;/p&gt;

&lt;p&gt;Combining multiple arrays (pieces or the whole thing).&lt;/p&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let dontChangeMe = ['Apples', 'Peaches', 'Detergent', 'Flowers'];
let meNeither = ['A shiny red polo', 'coffee', 'milk'];
let shoppingList = [
    ...dontChangeMe,
    'diapers',
    ...meNeither.slice(1)
]
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Copying an object and simultaneously updating properties.&lt;/p&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let nedStark = {
  name: 'Ned Stark',
  job: 'Warden of the North'
};
let newNed = { ...nedStark, job: 'Dead' };
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Converting a nodeList into an actual array.&lt;/p&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var divs = document.querySelectionAll('div')
var arrayOfDivs = [...divs] // returns an array not a nodelist
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;h3&gt;The Rest Operator&lt;/h3&gt;

&lt;p&gt;So, I haven’t personally found many use cases for the Rest Operator yet. However, I did stumble across this pattern for creating authenticated routes in React using React-Router. Here’s a basic example.&lt;/p&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const AuthenticatedRoute = ({ ...rest }) =&amp;gt; {
  const id = this.state;
  if (!id) {
    return &amp;lt;Redirect to={{ pathname: '/home' }} /&amp;gt;;
  }
  return &amp;lt;Route {...rest} /&amp;gt;;
};
// In Use
&amp;lt;AuthenticatedRoute
  path='/dashboard'
  data={this.state.data}
  render={() =&amp;gt; (
    &amp;lt;SomeComponent someProps={this.someProps} /&amp;gt;
  )}
/&amp;gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;The rest operator magic happens when you return &lt;code&gt;&amp;lt;Route {...rest} /&amp;gt;&lt;/code&gt; . Basically, what’s going on is a function AuthenticatedRoute is called and it checks for an id on the state object. If it fails, it returns a &lt;code&gt;&amp;lt;Redirect/&amp;gt;&lt;/code&gt; component. Otherwise, it returns a &lt;code&gt;&amp;lt;Route&amp;gt;&lt;/code&gt; component and passes through all its props (in this example &lt;code&gt;path&lt;/code&gt;, &lt;code&gt;data&lt;/code&gt;, and &lt;code&gt;render&lt;/code&gt;).&lt;/p&gt;

&lt;p&gt;Pretty handy right? Got anymore? Share them below please!&lt;/p&gt;


</description>
      <category>javascript</category>
      <category>es6</category>
      <category>spreadoperator</category>
      <category>react</category>
    </item>
  </channel>
</rss>
