<?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: Shawn Reisner</title>
    <description>The latest articles on Forem by Shawn Reisner (@sreisner).</description>
    <link>https://forem.com/sreisner</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%2F76056%2F13368218-93c3-4cd0-869d-dcc91d42e2c9.jpeg</url>
      <title>Forem: Shawn Reisner</title>
      <link>https://forem.com/sreisner</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/sreisner"/>
    <language>en</language>
    <item>
      <title>Here's Why Mapping a Constructed Array in JavaScript Doesn't Work</title>
      <dc:creator>Shawn Reisner</dc:creator>
      <pubDate>Fri, 15 Jun 2018 16:14:16 +0000</pubDate>
      <link>https://forem.com/sreisner/heres-why-mapping-a-constructed-array-in-javascript-doesnt-work-55di</link>
      <guid>https://forem.com/sreisner/heres-why-mapping-a-constructed-array-in-javascript-doesnt-work-55di</guid>
      <description>

&lt;h3&gt;
  
  
  Why Mapping a Constructed Array Doesn’t Work in JavaScript
&lt;/h3&gt;

&lt;h4&gt;
  
  
  And How To Do It Correctly
&lt;/h4&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--jrJDVyBu--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/892/1%2AbFIR37BFmQcxyPd7UPs6xg.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--jrJDVyBu--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/892/1%2AbFIR37BFmQcxyPd7UPs6xg.png" alt=""&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Scenario
&lt;/h3&gt;

&lt;p&gt;For the sake of demonstration, suppose you need to generate an array of numbers from 0 to 99. How might you do this? Here’s one option:&lt;/p&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const arr = [];

for (let i = 0; i &amp;lt; 100; i++) {
  arr[i] = i;
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;If you’re like me, seeing a traditional for-loop in JavaScript makes you slightly uncomfortable. In fact, I haven’t written a traditional for-loop in &lt;em&gt;years&lt;/em&gt; thanks to higher-order functions such as &lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach"&gt;forEach&lt;/a&gt;, &lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map"&gt;map&lt;/a&gt;, &lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter"&gt;filter&lt;/a&gt;, and &lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce"&gt;reduce&lt;/a&gt;. Declarative functional programming for the win!&lt;/p&gt;

&lt;p&gt;Maybe you haven’t yet &lt;a href="https://medium.com/javascript-scene/master-the-javascript-interview-what-is-functional-programming-7f218c68b3a0"&gt;drunk the functional programming Kool-aid&lt;/a&gt; and you’re thinking the above solution seems perfectly fine. It technically is, but after you’ve had a taste of the magic of higher-order functions, you’re probably thinking, “&lt;em&gt;There&lt;/em&gt; &lt;strong&gt;&lt;em&gt;must&lt;/em&gt;&lt;/strong&gt; &lt;em&gt;be a better way.&lt;/em&gt;”&lt;/p&gt;

&lt;p&gt;My first reaction to this problem was, “&lt;em&gt;I know! I’ll create an empty array of length 100 and map the indices to each element!&lt;/em&gt;” JavaScript allows you create an empty array of length &lt;em&gt;n&lt;/em&gt; with the Array constructor, like this:&lt;/p&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const arr = Array(100);
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Perfect, right? I have an array of length 100, so now I just need to map the index to each element.&lt;/p&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const arr = Array(100).map((_, i) =&amp;gt; i);

console.log(arr[0] === undefined); // true
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;What the h*ck!? The first element of the array should be &lt;em&gt;0&lt;/em&gt;, but it’s actually &lt;em&gt;undefined&lt;/em&gt;!&lt;/p&gt;

&lt;h3&gt;
  
  
  Explanation
&lt;/h3&gt;

&lt;p&gt;There’s an important technical distinction I need to make here in order to explain why this happened. Internally, JavaScript arrays &lt;strong&gt;are&lt;/strong&gt; objects, with numbers as keys. For example:&lt;/p&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;['a', 'b', 'c']
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;is essentially equivalent to this object:&lt;/p&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
  0: 'a',
  1: 'b',
  2: 'c',
  length: 3
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;When you access the element at index 0 in an array, you’re really just accessing an object property whose key is 0. This is important because when you think of arrays as objects in conjunction with the way these higher-order functions are implemented (don’t worry, I did that part for you), the cause of our problem makes perfect sense.&lt;/p&gt;

&lt;p&gt;When you create a new array with the Array constructor, it creates a new array object with its &lt;em&gt;length&lt;/em&gt; property set to the value you passed in, but otherwise &lt;em&gt;the object is a vacuum&lt;/em&gt;. There are no index keys in the object representation of the array whatsoever.&lt;/p&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
  //no index keys!
  length: 100
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;You get &lt;em&gt;undefined&lt;/em&gt; when you try to access the array value at index 0, but it’s not that the value &lt;em&gt;undefined&lt;/em&gt; is stored at index 0, it’s that the default behavior in JavaScript is to return &lt;em&gt;undefined&lt;/em&gt; if you try to access the value of an object for a key that does not exist.&lt;/p&gt;

&lt;p&gt;It just so happens that the higher-order functions &lt;em&gt;map&lt;/em&gt;, &lt;em&gt;reduce&lt;/em&gt;, &lt;em&gt;filter&lt;/em&gt;, and &lt;em&gt;forEach&lt;/em&gt; iterate over the index keys of the array object from 0 to &lt;em&gt;length&lt;/em&gt;, but the callback is only executed &lt;em&gt;if the key exists&lt;/em&gt; on the object. This explains why our callback is never called and nothing happens when we call the map function on the array — there are no index keys!&lt;/p&gt;

&lt;h3&gt;
  
  
  Solution
&lt;/h3&gt;

&lt;p&gt;As you now know, what we need is an array whose internal object representation contains a key for each number from 0 to &lt;em&gt;length&lt;/em&gt;. The best way to do this is to &lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax"&gt;spread the array&lt;/a&gt; out into an empty array.&lt;/p&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const arr = [...Array(100)].map((_, i) =&amp;gt; i);

console.log(arr[0]);
// 0
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Spreading the array into an empty array results in an array that’s filled with &lt;em&gt;undefined&lt;/em&gt; at each index.&lt;/p&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
  0: undefined,
  1: undefined,
  2: undefined,
  ...
  99: undefined,
  length: 100
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;This is because the spread operator is simpler than the map function. It simply loops through the array (or any iterable, really) from 0 to &lt;em&gt;length&lt;/em&gt; and creates a new index key in the enclosing array with the value returned from the spreading array at the current index. Since JavaScript returns &lt;em&gt;undefined&lt;/em&gt; from our spreading array at each of its indices (remember, it does this by default because it doesn’t have the index key for that value), we end up with a new array that’s actually filled with index keys, and therefore &lt;em&gt;map&lt;/em&gt;-able (and &lt;em&gt;reduce&lt;/em&gt;-able, &lt;em&gt;filter&lt;/em&gt;-able, and &lt;em&gt;forEach&lt;/em&gt;-able).&lt;/p&gt;

&lt;h3&gt;
  
  
  Conclusion
&lt;/h3&gt;

&lt;p&gt;We discovered some of the implications of arrays being internally represented as objects in Javascript, and learned the best way to create arrays of arbitrary length filled with whatever values you need.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;As always, leave your comments, questions, and feedback below!&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Happy coding! 👍&lt;/p&gt;

&lt;h3&gt;
  
  
  Follow me!
&lt;/h3&gt;

&lt;p&gt;If you liked this post, follow me! Or at least throw me a clap or two. You can spare one measly clap, right?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Medium&lt;/strong&gt; : &lt;a href="https://medium.com/@shawn.webdev"&gt;@shawn.webdev&lt;/a&gt;&lt;br&gt;
&lt;strong&gt;Twitter&lt;/strong&gt; : &lt;a href="https://twitter.com/ReisnerShawn"&gt;@ReisnerShawn&lt;/a&gt;&lt;br&gt;
&lt;strong&gt;dev.to&lt;/strong&gt; : &lt;a href="https://dev.to/sreisner"&gt;@sreisner&lt;/a&gt;&lt;br&gt;
&lt;strong&gt;Instagram&lt;/strong&gt; : &lt;a href="https://www.instagram.com/shawn.webdev"&gt;@shawn.webdev&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Check out more of my work
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://medium.com/p/49d74f555666"&gt;A Quick, Practical Use Case for ES6 Generators: Building an Infinitely Repeating Array&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://medium.com/p/6c199446b80c"&gt;Learn the React Context API With a Practical Example You Can Bring to Your Apps&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://medium.com/p/f55e6bd73434"&gt;Building a “Mask Toggle” Password Input Component w/ React and Material UI&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;





</description>
      <category>softwareengineering</category>
      <category>javascript</category>
      <category>programming</category>
      <category>softwaredevelopment</category>
    </item>
    <item>
      <title>Learn the React Context API with a Practical Example You Can Bring to Your Apps</title>
      <dc:creator>Shawn Reisner</dc:creator>
      <pubDate>Thu, 14 Jun 2018 01:34:48 +0000</pubDate>
      <link>https://forem.com/sreisner/understanding-the-react-context-api-through-building-a-shared-snackbar-for-in-app-notifications-8j2</link>
      <guid>https://forem.com/sreisner/understanding-the-react-context-api-through-building-a-shared-snackbar-for-in-app-notifications-8j2</guid>
      <description>

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--GPqrqLWk--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/512/1%2AtDxVH_WUqvu7fiNorh_EfQ.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--GPqrqLWk--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/512/1%2AtDxVH_WUqvu7fiNorh_EfQ.png" alt=""&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Preface
&lt;/h3&gt;

&lt;p&gt;Most apps need a way to unobtrusively display notifications to users as they happen. Suppose you're running a 20% off sale and you'd like to let your users know as soon as they sign in, or maybe after they submit feedback you want to display a thank you message.&lt;/p&gt;

&lt;p&gt;Material UI provides a snackbar component which is great for these types of messages, so I'll be using that for this example. That being said, this article is much more about the Context API than Material UI, and swapping out Material UI for any other component library would be very simple with this approach.&lt;/p&gt;

&lt;p&gt;Many apps need to trigger messages from dozens of different components. The React Context API makes it dead simple to provide all components access to a shared snackbar so they can trigger these messages without needing to implement separate components for each message. Here's how.&lt;/p&gt;

&lt;h3&gt;
  
  
  What We’re Building
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--r8xDldGs--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://cdn-images-1.medium.com/max/364/1%2Ad8iHKTMYovt37-tA1pF4mQ.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--r8xDldGs--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://cdn-images-1.medium.com/max/364/1%2Ad8iHKTMYovt37-tA1pF4mQ.gif" alt=""&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Setup/Dependencies
&lt;/h3&gt;

&lt;p&gt;This post assumes you already have a React app set up with &lt;strong&gt;@material-ui/core 1.0.0+&lt;/strong&gt; and &lt;strong&gt;@material-ui/icons 1.0.0+&lt;/strong&gt; installed as dependencies.&lt;/p&gt;

&lt;h3&gt;
  
  
  Creating the Context
&lt;/h3&gt;

&lt;p&gt;First, we need to create our Context API &lt;strong&gt;provider&lt;/strong&gt; and &lt;strong&gt;consumer&lt;/strong&gt; components. The &lt;strong&gt;provider&lt;/strong&gt; &lt;em&gt;provides&lt;/em&gt; the state of our snackbar, as well as some functions for manipulating that state, to all &lt;strong&gt;consumers&lt;/strong&gt;. This allows all child components to access and manipulate the &lt;strong&gt;provider&lt;/strong&gt; ’s state no matter how deep they are within the component hierarchy. No prop drilling required!&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;  &lt;/div&gt;

&lt;p&gt;The first step is creating a context by calling &lt;em&gt;React.createContext()&lt;/em&gt;. The object returned contains two properties, Provider and Consumer. We use these to build out the components that will manage and interact with the snackbar’s state.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;From here on out, when I use the terms “provider” and “consumer”, I’m referring to the&lt;/em&gt; &lt;strong&gt;&lt;em&gt;SharedSnackbarProvider&lt;/em&gt;&lt;/strong&gt; &lt;em&gt;and&lt;/em&gt; &lt;strong&gt;&lt;em&gt;SharedSnackbarConsumer&lt;/em&gt;&lt;/strong&gt; &lt;em&gt;components from this section.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;As you can see, our provider is a pretty standard component. In its &lt;em&gt;render&lt;/em&gt; function, we render a &lt;strong&gt;SharedSnackbarContext.Provider&lt;/strong&gt; component with a &lt;em&gt;value&lt;/em&gt; prop. The object passed to the &lt;em&gt;value&lt;/em&gt; prop is what consumers will be able to access so they can interact with our snackbar. For lack of a better term, this is the &lt;strong&gt;API&lt;/strong&gt; for our shared snackbar component.&lt;/p&gt;

&lt;p&gt;Take note of the &lt;em&gt;TODO&lt;/em&gt; on line 41. Eventually we’ll be rendering the actual snackbar &lt;em&gt;within&lt;/em&gt; the context provider’s &lt;em&gt;render&lt;/em&gt; function as a sibling to its children. This ensures that when the provider is rendered, all children will be using the same exact snackbar component.&lt;/p&gt;

&lt;h3&gt;
  
  
  Creating the Shared Snackbar Component
&lt;/h3&gt;

&lt;p&gt;Now we need to build the presentation component responsible for rendering the snackbar UI based on the state of the provider. This component will use the consumer to access the properties it needs for rendering.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;  &lt;/div&gt;

&lt;p&gt;Here we’ve built a component that renders the snackbar UI in a function within the &lt;strong&gt;SharedSnackbarConsumer&lt;/strong&gt; component. The argument to the function is the &lt;em&gt;value&lt;/em&gt; prop object we exposed from our provider. As a result, when the state of the provider is updated, it will trigger the snackbar component to rerender.&lt;/p&gt;

&lt;p&gt;Now we can render this component in our provider’s &lt;em&gt;render&lt;/em&gt; function.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;  &lt;/div&gt;

&lt;h3&gt;
  
  
  Rendering the Provider
&lt;/h3&gt;

&lt;p&gt;At this point, we’re almost finished with the infrastructure. There’s just one last thing to do, which is to render the provider within our app. I’m going to place the provider at the root of the entire app so that all children have access to the snackbar.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;  &lt;/div&gt;

&lt;h3&gt;
  
  
  Opening the Snackbar from Child Components
&lt;/h3&gt;

&lt;p&gt;Now, &lt;strong&gt;ButtonA&lt;/strong&gt; and &lt;strong&gt;ButtonB&lt;/strong&gt; can render their UI and trigger in-app messages without needing to directly receive props from the root of the app! 🤙&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;  &lt;/div&gt;

&lt;h3&gt;
  
  
  Summary
&lt;/h3&gt;

&lt;p&gt;In summary, here’s what happening.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;First, we created a &lt;strong&gt;context provider&lt;/strong&gt; component which manages the global state for our snackbar.&lt;/li&gt;
&lt;li&gt;We then created a component that renders the snackbar’s UI based on the state of the provider. This component subscribes to the provider state in its render function via a &lt;strong&gt;context consumer&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;Finally, we rendered two buttons that update the state of the &lt;strong&gt;context provider&lt;/strong&gt; with the &lt;em&gt;openSnackbar&lt;/em&gt; function, which was passed to them via a &lt;strong&gt;context consumer&lt;/strong&gt;. This results in the changes propagating down to the snackbar component, triggering a re-render.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Material UI provides a number of other snackbar features I did not implement with this example, such as action buttons and color customization. For the sake of simplicity I didn’t add the ability to customize those features. Adding that logic yourself would be a great next step if you’re really looking to learn the Context API!&lt;/p&gt;

&lt;p&gt;Thank you so much for taking the time to improve yourself. If you found this article useful in any way, I will always accept a clap or two. While you’re at it, take a few seconds and follow me for more great content:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://dev.to/sreisner/a-quick-practical-use-case-for-es6-generators-building-an-infinitely-repeating-array-1onk"&gt;A Quick, Practical Use Case for ES6 Generators: Building an Infinitely Repeating Array&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://dev.to/sreisner/building-a-mask-toggle-password-input-component-w-react-and-material-ui-37m3"&gt;Building a “Mask Toggle” Password Input Component w/ React and Material UI&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Twitter&lt;/strong&gt; : &lt;a href="https://twitter.com/ReisnerShawn"&gt;@ReisnerShawn&lt;/a&gt;&lt;br&gt;&lt;br&gt;
&lt;strong&gt;dev.to&lt;/strong&gt; : &lt;a href="https://dev.to/sreisner"&gt;@sreisner&lt;/a&gt;&lt;br&gt;&lt;br&gt;
&lt;strong&gt;Instagram&lt;/strong&gt; : &lt;a href="https://www.instagram.com/shawn.webdev"&gt;@shawn.webdev&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Happy coding!&lt;/p&gt;


</description>
      <category>react</category>
      <category>webdev</category>
      <category>materialdesign</category>
    </item>
    <item>
      <title>A Quick, Practical Use Case for ES6 Generators: Building an Infinitely Repeating Array</title>
      <dc:creator>Shawn Reisner</dc:creator>
      <pubDate>Wed, 06 Jun 2018 13:06:07 +0000</pubDate>
      <link>https://forem.com/sreisner/a-quick-practical-use-case-for-es6-generators-building-an-infinitely-repeating-array-1onk</link>
      <guid>https://forem.com/sreisner/a-quick-practical-use-case-for-es6-generators-building-an-infinitely-repeating-array-1onk</guid>
      <description>&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--_nzSaA-V--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://thepracticaldev.s3.amazonaws.com/i/6mytns4vyiea6h7gtsew.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--_nzSaA-V--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://thepracticaldev.s3.amazonaws.com/i/6mytns4vyiea6h7gtsew.png" alt=""&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Preface
&lt;/h3&gt;

&lt;p&gt;You’ve probably heard of ES6 generators, perhaps you’ve even learned the syntax, and you may be wondering what they’re actually useful for in real life.&lt;/p&gt;

&lt;h4&gt;
  
  
  Definition (from &lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*"&gt;MDN&lt;/a&gt;)
&lt;/h4&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;Generators are functions which can be exited and later re-entered. Their context (variable bindings) will be saved across re-entrances.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;You may be thinking, “&lt;em&gt;Okay, but why would I want to do that?&lt;/em&gt;” As it turns out, there are a whole range of use cases ranging from simple to complex, many of which involve Promises to make asynchronous requests (async/await is built on top of generators). My goal is to give you the first baby step into understanding how they work with a simple, real-life example so that you begin noticing when a generator is the most suitable solution to problems in your own code. Here we go.&lt;/p&gt;

&lt;h3&gt;
  
  
  Use Case
&lt;/h3&gt;

&lt;p&gt;I’m building an app in which my users can calculate a 3-week workout cycle, with a setting to work out between 3 and 7 days per week during the cycle. Each individual workout is based on one of the following 4 lifts: &lt;em&gt;squat&lt;/em&gt;, &lt;em&gt;bench press&lt;/em&gt;, &lt;em&gt;deadlift&lt;/em&gt;, and &lt;em&gt;overhead press&lt;/em&gt;, and each successive workout must be based on the next lift in that order:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Squat&lt;/li&gt;
&lt;li&gt;Bench&lt;/li&gt;
&lt;li&gt;Deadlift&lt;/li&gt;
&lt;li&gt;Overhead press&lt;/li&gt;
&lt;li&gt;Squat&lt;/li&gt;
&lt;li&gt;Bench&lt;/li&gt;
&lt;li&gt;Deadlift&lt;/li&gt;
&lt;li&gt;Overhead press&lt;/li&gt;
&lt;li&gt;…&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;You can probably see where this is going.&lt;/p&gt;

&lt;p&gt;I need my code to say, “&lt;em&gt;Give me the lift for the next workout, then the next, then the next, etc. When the end of the list of lifts is reached, start over from the beginning and keep repeating forever, until I’ve generated all the workouts for the 3-week cycle.&lt;/em&gt;” Here’s a simplified version of how I initially implemented it, &lt;strong&gt;without&lt;/strong&gt; generators:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Not &lt;em&gt;too&lt;/em&gt; bad, but it could be more declarative. Wouldn’t it be nice if we didn’t have to keep track of that &lt;em&gt;currentLiftIndex&lt;/em&gt; directly in our workout generation code? It decreases the readability of the code and feels like it belongs in its own function. Here’s the code using a generator function, I’ll explain it below.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Here, the code is more declarative and readable. We abstracted the index-tracking logic into a general-purpose utility function called &lt;em&gt;repeatedArray&lt;/em&gt;. The &lt;em&gt;function *&lt;/em&gt; syntax tells JavaScript that this is a generator function. All we have to do is ask for the next item in the “repeated array” and our generator gives it to us. The best part is &lt;strong&gt;we don’t have to worry about how it’s happening outside of our generator function.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Here’s what’s happening:&lt;/p&gt;

&lt;p&gt;&lt;em&gt;repeatedArray&lt;/em&gt; returns an &lt;strong&gt;iterator&lt;/strong&gt; object &lt;em&gt;for the repeatedArray function itself&lt;/em&gt; (read that twice) when we call it on line 9. The iterator is stored in a variable named &lt;em&gt;nextLiftGenerator&lt;/em&gt;. It’s important to understand that the code in the function hasn’t been executed at this point. The function is only executed when we call the &lt;em&gt;next()&lt;/em&gt; function on the &lt;em&gt;nextLiftGenerator&lt;/em&gt; iterable, and it’s only executed up until it hits a &lt;em&gt;yield&lt;/em&gt;. Our generator gives us the value, then waits until the next call to continue execution until it hits another &lt;em&gt;yield&lt;/em&gt;, then returns that value. Make sense? That’s it!&lt;/p&gt;

&lt;p&gt;This is obviously a very simple example, but hopefully it helped you understand how generators work, and also why generators are such a powerful feature in JavaScript.&lt;/p&gt;

&lt;p&gt;If you liked this article, follow me on &lt;a href="https://twitter.com/ReisnerShawn"&gt;Twitter&lt;/a&gt; and &lt;a href="https://www.instagram.com/shawn.webdev/"&gt;Instagram&lt;/a&gt; for more nerdy content!&lt;/p&gt;

&lt;p&gt;Happy coding!&lt;/p&gt;




</description>
      <category>javascript</category>
      <category>tutorial</category>
      <category>generator</category>
      <category>arrays</category>
    </item>
    <item>
      <title>Building a “Mask Toggle” Password Input Component w/ React and Material UI</title>
      <dc:creator>Shawn Reisner</dc:creator>
      <pubDate>Mon, 04 Jun 2018 17:03:13 +0000</pubDate>
      <link>https://forem.com/sreisner/building-a-mask-toggle-password-input-component-w-react-and-material-ui-37m3</link>
      <guid>https://forem.com/sreisner/building-a-mask-toggle-password-input-component-w-react-and-material-ui-37m3</guid>
      <description>&lt;p&gt;As everyone knows by now, allowing users to toggle password input visibility removes friction and improves user experience. I’ll show you how to build a toggleable password input in this tutorial!&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ftyxcergaic0iv76mk4r4.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ftyxcergaic0iv76mk4r4.gif"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Setup/Dependencies
&lt;/h3&gt;

&lt;p&gt;This article assumes you already have a React app set up with &lt;strong&gt;@material-ui/core 1.0.0+&lt;/strong&gt; and &lt;strong&gt;@material-ui/icons 1.0.0+&lt;/strong&gt; installed as dependencies. If you need help with this this, start &lt;a href="https://reactjs.org/docs/add-react-to-a-new-app.html" rel="noopener noreferrer"&gt;here&lt;/a&gt;, then go &lt;a href="https://material-ui.com" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  Building the Component
&lt;/h3&gt;

&lt;p&gt;First, we start with our &lt;strong&gt;PasswordInput&lt;/strong&gt; class component that renders a Material UI TextField.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Here we’ve got ourselves a standard password input.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fs5lsjqz6eqth5opbf8ji.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fs5lsjqz6eqth5opbf8ji.gif"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;It’s worth noting that I spread the component’s props onto the rendered TextField. This allows you to treat the PasswordInput component just as you would a TextField component with a type of password.&lt;/p&gt;

&lt;p&gt;Before getting into the mask/unmask button logic, it’s important to understand that in Material UI, the &lt;strong&gt;TextField&lt;/strong&gt; component is basically just a wrapper around an &lt;strong&gt;Input&lt;/strong&gt; component. Since you might want to customize the underlying props of the &lt;strong&gt;Input&lt;/strong&gt; , Material UI provides a prop on the &lt;strong&gt;TextField&lt;/strong&gt; called &lt;em&gt;InputProps&lt;/em&gt; that lets you pass custom props through the &lt;strong&gt;TextField&lt;/strong&gt; and into the underlying &lt;strong&gt;Input&lt;/strong&gt;. Make sense? It just so happens that the &lt;strong&gt;Input&lt;/strong&gt; component has an important prop we need to pass to it through the &lt;strong&gt;TextField&lt;/strong&gt; , called &lt;em&gt;endAdornment&lt;/em&gt;. Here’s the code.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Take a look at lines 15–31. This gives us a nice icon embedded to the right within the input. Let’s make it actually toggle the mask.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Here we added a &lt;em&gt;passwordIsMasked&lt;/em&gt; state property to the component and then toggle it when the eye is clicked. When the property is toggled, it triggers a rerender of the component as either password or a text input.&lt;/p&gt;

&lt;p&gt;Styles were added to the icon to change the cursor to a pointer when the user clicks it as well.&lt;/p&gt;

&lt;p&gt;And there you have it, we’re done!&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fhtw8sfapfr2prjskstw8.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fhtw8sfapfr2prjskstw8.gif"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;If you found this post useful, feel free to throw some applause my way, leave a comment, or follow me on here or on social media (my &lt;a href="https://www.instagram.com/shawn.webdev/" rel="noopener noreferrer"&gt;Instagram&lt;/a&gt; is on fire lately)!&lt;/p&gt;




</description>
      <category>react</category>
      <category>ux</category>
      <category>materialui</category>
      <category>javascript</category>
    </item>
  </channel>
</rss>
