<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Tyler McGinnis on Medium]]></title>
        <description><![CDATA[Stories by Tyler McGinnis on Medium]]></description>
        <link>https://medium.com/@tylermcginnis?source=rss-c52389e3ee63------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*vU4NFEffXFZc77PVSAu6tg.jpeg</url>
            <title>Stories by Tyler McGinnis on Medium</title>
            <link>https://medium.com/@tylermcginnis?source=rss-c52389e3ee63------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 18 May 2026 11:30:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tylermcginnis/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com" rel="hub"/>
        <item>
            <title><![CDATA[Why React Hooks?]]></title>
            <link>https://medium.com/dailyjs/why-react-hooks-2d72a849a0e6?source=rss-c52389e3ee63------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d72a849a0e6</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Tyler McGinnis]]></dc:creator>
            <pubDate>Mon, 29 Jul 2019 00:00:00 GMT</pubDate>
            <atom:updated>2019-08-01T11:30:50.364Z</atom:updated>
            <content:encoded><![CDATA[<p>This was originally published at <a href="https://tylermcginnis.com/why-react-hooks/">TylerMcGinnis.com</a> and is part of the <a href="https://tylermcginnis.com/courses/react-hooks/">React Hooks</a> course. If you enjoy this post, check it out.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*4877k4Hq9dPdtmvg9hnGFA.jpeg" /></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FeX_L39UvZes%3Ffeature%3Doembed&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DeX_L39UvZes&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FeX_L39UvZes%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/c1a9b57bd0d6ab57f3381864551efe06/href">https://medium.com/media/c1a9b57bd0d6ab57f3381864551efe06/href</a></iframe><p>The first thing you should do whenever you’re about to learn something new is ask yourself two questions -</p><ol><li>Why does this thing exist?</li><li>What problems does this thing solve?</li></ol><p>If you never develop a convincing answer for both of those questions, you won’t have a solid enough foundation to build upon when you dive into the specifics. These questions are specifically interesting in regards to <a href="https://tylermcginnis.com/courses/react-hooks/">React Hooks</a>. React was the <a href="https://insights.stackoverflow.com/survey/2019">most popular and most loved front-end framework</a> in the JavaScript ecosystem when Hooks were released. Despite the existing praise, the React team still saw it necessary to build and release Hooks. Lost in the various Medium posts and blog think pieces on Hooks are the reasons <strong>(1) why</strong> and for what <strong>(2) benefit</strong>, despite high praise and popularity, the React team decided to spend valuable resources building and releasing Hooks. To better understand the answers to both of these questions, we first need to take a deeper look into how we’ve historically written React apps.</p><h3>createClass</h3><p>If you’ve been around the React game long enough, you’ll remember the React.createClass API. It was the original way in which we&#39;d create React components. All of the information you&#39;d use to describe the component would be passed as an object to createClass.</p><pre>const ReposGrid = React.createClass({<br>  getInitialState () {<br>    return {<br>      repos: [],<br>      loading: true<br>    }<br>  },<br>  componentDidMount () {<br>    this.updateRepos(this.props.id)<br>  },<br>  componentDidUpdate (prevProps) {<br>    if (prevProps.id !== this.props.id) {<br>      this.updateRepos(this.props.id)<br>    }<br>  },<br>  updateRepos (id) {<br>    this.setState({ loading: true })</pre><pre>    fetchRepos(id)<br>      .then((repos) =&gt; this.setState({<br>        repos,<br>        loading: false<br>      }))<br>  },<br>  render() {<br>    const { loading, repos } = this.state</pre><pre>    if (loading === true) {<br>      return &lt;Loading /&gt;<br>    }</pre><pre>  return (<br>      &lt;ul&gt;<br>        {repos.map(({ name, handle, stars, url }) =&gt; (<br>          &lt;li key={name}&gt;<br>            &lt;ul&gt;<br>              &lt;li&gt;&lt;a href={url}&gt;{name}&lt;/a&gt;&lt;/li&gt;<br>              &lt;li&gt;@{handle}&lt;/li&gt;<br>              &lt;li&gt;{stars} stars&lt;/li&gt;<br>            &lt;/ul&gt;<br>          &lt;/li&gt;<br>        ))}<br>      &lt;/ul&gt;<br>    )<br>  }<br>})</pre><p><a href="https://codesandbox.io/s/why-react-hooks-createclass-iw6s5"><strong>💻 Play with the code.</strong></a></p><p>createClass was a simple and effective way to create React components. The reason React initially used the createClass API was because, at the time, JavaScript didn&#39;t have a built-in class system. Of course, this eventually changed. With ES6, JavaScript introduced the class keyword and with it a native way to create classes in JavaScript. This put React in a tough position. Either continue using createClass and fight against the progression of JavaScript or submit to the will of the EcmaScript standard and embrace classes. As history has shown, they chose the later.</p><h3>React.Component</h3><blockquote><em>We figured that we’re not in the business of designing a class system. We just want to use whatever is the idiomatic JavaScript way of creating classes. — </em><a href="https://reactjs.org/blog/2015/01/27/react-v0.13.0-beta-1.html"><em>React v0.13.0 Release</em></a></blockquote><p>React v0.13.0 introduced the React.Component API which allowed you to create React components from (now) native JavaScript classes. This was a big win as it better aligned React with the EcmaScript standard.</p><pre>class ReposGrid extends React.Component {<br>  constructor (props) {<br>    super(props)</pre><pre>    this.state = {<br>      repos: [],<br>      loading: true<br>    }</pre><pre>    this.updateRepos = this.updateRepos.bind(this)<br>  }<br>  componentDidMount () {<br>    this.updateRepos(this.props.id)<br>  }<br>  componentDidUpdate (prevProps) {<br>    if (prevProps.id !== this.props.id) {<br>      this.updateRepos(this.props.id)<br>    }<br>  }<br>  updateRepos (id) {<br>    this.setState({ loading: true })</pre><pre>    fetchRepos(id)<br>      .then((repos) =&gt; this.setState({<br>        repos,<br>        loading: false<br>      }))<br>  }<br>  render() {<br>    if (this.state.loading === true) {<br>      return &lt;Loading /&gt;<br>    }</pre><pre>    return (<br>      &lt;ul&gt;<br>        {this.state.repos.map(({ name, handle, stars, url }) =&gt; (<br>          &lt;li key={name}&gt;<br>            &lt;ul&gt;<br>              &lt;li&gt;&lt;a href={url}&gt;{name}&lt;/a&gt;&lt;/li&gt;<br>              &lt;li&gt;@{handle}&lt;/li&gt;<br>              &lt;li&gt;{stars} stars&lt;/li&gt;<br>            &lt;/ul&gt;<br>          &lt;/li&gt;<br>        ))}<br>      &lt;/ul&gt;<br>    )<br>  }<br>}</pre><p><a href="https://codesandbox.io/s/why-react-hooks-reactcomponent-xdhg5"><strong>💻 Play with the code.</strong></a></p><p>Though a clear step in the right direction, React.Component wasn&#39;t without its trade-offs.</p><h3>constructor</h3><p>With Class components, you initialize the state of the component inside of the constructor method as a state property on the instance ( this). However, according to the ECMAScript spec, if you&#39;re extending a subclass (in this case, React.Component), you must first invoke super before you can use this. Specifically, when using React, you also have to remember to pass props to super.</p><pre>constructor (props) {<br>    super(props) // 🤮</pre><pre>    ...<br>}</pre><h3><strong>Autobinding</strong></h3><p>When using createClass, React would auto-magically bind all the methods to the component&#39;s instance, this. With React.Component, that wasn&#39;t the case. Very quickly, <a href="https://stackoverflow.com/questions/32317154/react-uncaught-typeerror-cannot-read-property-setstate-of-undefined">React developers everywhere</a> realized they didn&#39;t know how <a href="https://tylermcginnis.com/this-keyword-call-apply-bind-javascript/">the <strong>this</strong> keyword</a> worked. Instead of having method invocations that &quot;just worked&quot;, you had to remember to .bind methods in the class&#39;s constructor. If you didn&#39;t, you&#39;d get the popular &quot;Cannot read property setState of undefined&quot; error.</p><pre><br>  constructor (props) {<br>    ...</pre><pre>    this.updateRepos = this.updateRepos.bind(this) // 😭<br>  }</pre><p>Now I know what you might be thinking. First, these issues are pretty superficial. Sure calling super(props) and remembering to bind your methods is annoying, but there&#39;s nothing fundamentally wrong here. Second, these aren&#39;t necessarily even issues with React as much as they are with the way JavaScript classes were designed. Both points are valid. However, we&#39;re developers. Even the most superficial issues become a nuisance when you&#39;re dealing with them 20+ times a day. Luckily for us, shortly after the switch from createClass to React.Component, the <a href="https://tylermcginnis.com/javascript-private-and-public-class-fields/">Class Fields</a> proposal was created.</p><h3>Class Fields</h3><p>Class fields allow you to add instance properties directly as a property on a class without having to use constructor. What that means for us is that with Class Fields, both of our &quot;superficial&quot; issues we previously talked about would be solved. We no longer need to use constructor to set the initial state of the component and we no longer need to .bind in the constructor since we could use arrow functions for our methods.</p><pre>class ReposGrid extends React.Component {<br>  state = {<br>    repos: [],<br>    loading: true<br>  }<br>  componentDidMount () {<br>    this.updateRepos(this.props.id)<br>  }<br>  componentDidUpdate (prevProps) {<br>    if (prevProps.id !== this.props.id) {<br>      this.updateRepos(this.props.id)<br>    }<br>  }<br>  updateRepos = (id) =&gt; {<br>    this.setState({ loading: true })</pre><pre>    fetchRepos(id)<br>      .then((repos) =&gt; this.setState({<br>        repos,<br>        loading: false<br>      }))<br>  }<br>  render() {<br>    const { loading, repos } = this.state</pre><pre>    if (loading === true) {<br>      return &lt;Loading /&gt;<br>    }</pre><pre>    return (<br>      &lt;ul&gt;<br>        {repos.map(({ name, handle, stars, url }) =&gt; (<br>          &lt;li key={name}&gt;<br>            &lt;ul&gt;<br>              &lt;li&gt;&lt;a href={url}&gt;{name}&lt;/a&gt;&lt;/li&gt;<br>              &lt;li&gt;@{handle}&lt;/li&gt;<br>              &lt;li&gt;{stars} stars&lt;/li&gt;<br>            &lt;/ul&gt;<br>          &lt;/li&gt;<br>        ))}<br>      &lt;/ul&gt;<br>    )<br>  }<br>}</pre><p><a href="https://codesandbox.io/s/why-react-hooks-class-fields-9tbis"><strong>💻 Play with the code.</strong></a></p><p>So now we’re good, right? Unfortunately, no. The move from createClass to React.Component came with some tradeoffs, but as we saw, Class Fields took care of those. Unfortunately, there are still some more profound (but less talked about) issues that exist with all the previous versions we&#39;ve seen.</p><p>The whole idea of React is that you’re better able to manage the complexity of your application by breaking it down into separate components that you then can compose together. This component model is what makes React so elegant. It’s what makes React, React. The problem, however, doesn’t lie in the component model, but in how the component model is implemented.</p><h3>Duplicate Logic</h3><p>Historically, how we’ve structured our React components has been coupled to the component’s lifecycle. This divide naturally forces us to sprinkle related logic throughout the component. We can clearly see this in the ReposGrid example we&#39;ve been using. We need three separate methods ( componentDidMount, componentDidUpdate, and updateRepos) to accomplish the same thing - keep repos in sync with whatever props.id is.</p><pre>  componentDidMount () {<br>    this.updateRepos(this.props.id)<br>  }<br>  componentDidUpdate (prevProps) {<br>    if (prevProps.id !== this.props.id) {<br>      this.updateRepos(this.props.id)<br>    }<br>  }<br>  updateRepos = (id) =&gt; {<br>    this.setState({ loading: true })</pre><pre>    fetchRepos(id)<br>      .then((repos) =&gt; this.setState({<br>        repos,<br>        loading: false<br>      }))<br>  }</pre><p>To fix this, we’d need a whole new paradigm for the way in which we’d handle side effects in React components.</p><h3>Sharing Non-visual Logic</h3><p>When you think about composition in React, odds are you think in terms of UI composition. This is natural since it’s what React is so good at.</p><p>Realistically, there’s more to building an app than just the UI layer. It’s not uncommon to need to compose and reuse non-visual logic. However, because React couples UI to a component, this can be difficult. Historically, React hasn’t had a great answer for this.</p><p>Sticking with our example, say we needed to create another component that also needed the repos state. Right now, that state and the logic for handling it lives inside of the ReposGrid component. How would we approach this? Well, the simplest approach would be to copy all of the logic for fetching and handling our repos and paste it into the new component. Tempting, but nah. A smarter approach would be to create a <a href="https://tylermcginnis.com/react-higher-order-components/">Higher-Order Component</a> that encapsulated all of the shared logic and passed loading and repos as props to whatever component needed it.</p><pre>function withRepos (Component) {<br>  return class WithRepos extends React.Component {<br>    state = {<br>      repos: [],<br>      loading: true<br>    }<br>    componentDidMount () {<br>      this.updateRepos(this.props.id)<br>    }<br>    componentDidUpdate (prevProps) {<br>      if (prevProps.id !== this.props.id) {<br>        this.updateRepos(this.props.id)<br>      }<br>    }<br>    updateRepos = (id) =&gt; {<br>      this.setState({ loading: true })</pre><pre>      fetchRepos(id)<br>        .then((repos) =&gt; this.setState({<br>          repos,<br>          loading: false<br>        }))<br>    }<br>    render () {<br>      return (<br>        &lt;Component<br>          {...this.props}<br>          {...this.state}<br>        /&gt;<br>      )<br>    }<br>  }<br>}</pre><p>Now whenever any component in our app needed repos (or loading), we could wrap it in our withRepos HOC.</p><pre>// ReposGrid.js<br>function ReposGrid ({ loading, repos }) {<br>  ...<br>}</pre><pre>export default withRepos(ReposGrid)</pre><pre><br>// Profile.js<br>function Profile ({ loading, repos }) {<br>  ...<br>}</pre><pre>export default withRepos(Profile)</pre><p><a href="https://codesandbox.io/s/why-react-hooks-withrepos-okjsj"><strong>💻 Play with the code.</strong></a></p><p>This works and historically (along with <a href="https://tylermcginnis.com/react-render-props/">Render Props</a>) has been the recommended solution for sharing non-visual logic. However, both these patterns have some downsides.</p><p>First, if you’re not familiar with them (and even when you are), your brain can get a little wonky following the logic. With our withRepos HOC, we have a function that takes the eventually rendered component as the first argument but returns a new class component which is where our logic lives. What a convoluted process.</p><p>Next, what if we had more than one HOC we were consuming. As you can imagine, it gets out of hand pretty quickly.</p><pre>export default withHover(<br>  withTheme(<br>    withAuth(<br>      withRepos(Profile)<br>    )<br>  )<br>)</pre><p>Worse than ^ is what eventually gets rendered. HOCs (and similar patterns) force you to restructure and wrap your components. This can eventually lead to “wrapper hell” which again, makes it harder to follow.</p><pre>&lt;WithHover&gt;<br>  &lt;WithTheme hovering={false}&gt;<br>    &lt;WithAuth hovering={false} theme=&#39;dark&#39;&gt;<br>      &lt;WithRepos hovering={false} theme=&#39;dark&#39; authed={true}&gt;<br>        &lt;Profile <br>          id=&#39;JavaScript&#39;<br>          loading={true} <br>          repos={[]}<br>          authed={true}<br>          theme=&#39;dark&#39;<br>          hovering={false}<br>        /&gt;<br>      &lt;/WithRepos&gt;<br>    &lt;/WithAuth&gt;<br>  &lt;WithTheme&gt;<br>&lt;/WithHover&gt;</pre><h3>Current State</h3><p>So here’s where we’re at.</p><ul><li>React is hella popular.</li><li>We use Classes for React components cause that’s what made the most sense at the time.</li><li>Calling super(props) is annoying.</li><li>No one knows how “this” works.</li><li>OK, calm down. I know YOU know how “this” works, but it’s an unnecessary hurdle for some.</li><li>Organizing our components by lifecycle methods forces us to sprinkle related logic throughout our components.</li><li>React has no good primitive for sharing non-visual logic.</li></ul><p>Now we need a new component API that solves all of those problems while remaining <strong>simple</strong>, <strong>composable</strong>, <strong>flexible</strong>, and <strong>extendable</strong>. Quite the task, but somehow the React team pulled it off.</p><h3>React Hooks</h3><p>Since React v0.14.0, we’ve had two ways to create components — classes or functions. The difference was that if our component had state or needed to utilize a lifecycle method, we had to use a class. Otherwise, if it just accepted props and rendered some UI, we could use a function.</p><p>Now, what if this wasn’t the case. What if instead of ever having to use a class, we could just always use a function.</p><blockquote><em>Sometimes, the elegant implementation is just a function. Not a method. Not a class. Not a framework. Just a function.</em></blockquote><blockquote><em>- John Carmack. Oculus VR CTO.</em></blockquote><p>Sure we’d need to figure out a way to add the ability for functional components to have state and lifecycle methods, but assuming we did that, what benefits would we see?</p><p>Well, we would no longer have to call super(props), we&#39;d no longer need to worry about binding our methods or the this keyword, and we&#39;d no longer have a use for Class Fields. Essentially, all of the &quot;superficial&quot; issues we talked about earlier would go away.</p><p>Now, the harder issues.</p><ul><li>State</li><li>Lifecycle methods</li><li>Sharing non-visual logic</li></ul><h3>State</h3><p>Since we’re no longer using classes or this, we need a new way to add and manage state inside of our components. As of React v16.8.0, React gives us this new way via the useState method.</p><blockquote><em>useState is the first of many &quot;Hooks&quot; you&#39;ll be seeing in this course. Let the rest of this post serve as a soft introduction. We&#39;ll be diving much deeper into </em><em>useState as well as other Hooks in future sections.</em></blockquote><p>useState takes in a single argument, the initial value for the state. What it returns is an array with the first item being the piece of state and the second item being a function to update that state.</p><pre>const loadingTuple = React.useState(true)<br>const loading = loadingTuple[0]<br>const setLoading = loadingTuple[1]</pre><pre>...</pre><pre>loading // true<br>setLoading(false)<br>loading // false</pre><p>As you can see, grabbing each item in the array individually isn’t the best developer experience. This is just to demonstrate how useState returns an array. Typically, you&#39;d use Array Destructuring to grab the values in one line.</p><pre>// const loadingTuple = React.useState(true)<br>// const loading = loadingTuple[0]<br>// const setLoading = loadingTuple[1]</pre><pre>const [ loading, setLoading ] = React.useState(true) // 👌</pre><p>Now let’s update our ReposGrid component with our new found knowledge of the useState Hook.</p><pre>function ReposGrid ({ id }) {<br>  const [ repos, setRepos ] = React.useState([])<br>  const [ loading, setLoading ] = React.useState(true)</pre><pre>  if (loading === true) {<br>    return &lt;Loading /&gt;<br>  }</pre><pre>  return (<br>    &lt;ul&gt;<br>      {repos.map(({ name, handle, stars, url }) =&gt; (<br>        &lt;li key={name}&gt;<br>          &lt;ul&gt;<br>            &lt;li&gt;&lt;a href={url}&gt;{name}&lt;/a&gt;&lt;/li&gt;<br>            &lt;li&gt;@{handle}&lt;/li&gt;<br>            &lt;li&gt;{stars} stars&lt;/li&gt;<br>          &lt;/ul&gt;<br>        &lt;/li&gt;<br>      ))}<br>    &lt;/ul&gt;<br>  )<br>}</pre><p><a href="https://codesandbox.io/s/why-react-hooks-usestate-ddhc4"><strong>💻 Play with the code.</strong></a></p><ul><li>State ✅</li><li>Lifecycle methods</li><li>Sharing non-visual logic</li></ul><h3>Lifecycle methods</h3><p>Here’s something that may make you sad (or happy?). When using React Hooks, I want you to take everything you know about the traditional React lifecycle methods as well as that way of thinking, and forget it. We’ve already seen the problem of thinking in terms of the lifecycle of a component — “This [lifecycle] divide naturally forces us to sprinkle related logic throughout the component.” Instead, think in terms of <strong>synchronization</strong>.</p><p>Think of any time you’ve ever used a lifecycle event. Whether it was to set the initial state of the component, fetch data, update the DOM, anything — the end goal was always synchronization. Typically, synchronizing something outside of React land (an API request, the DOM, etc.) with something inside of React land (component state) or vice versa.</p><p>When we think in terms of synchronization instead of lifecycle events, it allows us to group together related pieces of logic. To do this, React gives us another Hook called useEffect.</p><p>Defined, useEffect lets you perform side effects in function components. It takes two arguments, a function, and an optional array. The function defines which side effects to run and the (optional) array defines when to &quot;re-sync&quot; (or re-run) the effect.</p><pre>React.useEffect(() =&gt; {<br>  document.title = `Hello, ${username}`<br>}, [username])</pre><p>In the code above, the function passed to useEffect will run whenever username changes. Therefore, syncing the document&#39;s title with whatever Hello, ${username} resolves to.</p><p>Now, how can we use the useEffect Hook inside of our code to sync repos with our fetchRepos API request?</p><pre>function ReposGrid ({ id }) {<br>  const [ repos, setRepos ] = React.useState([])<br>  const [ loading, setLoading ] = React.useState(true)</pre><pre>  React.useEffect(() =&gt; {<br>    setLoading(true)</pre><pre>    fetchRepos(id)<br>      .then((repos) =&gt; {<br>        setRepos(repos)<br>        setLoading(false)<br>      })<br>  }, [id])</pre><pre>  if (loading === true) {<br>    return &lt;Loading /&gt;<br>  }</pre><pre>  return (<br>    &lt;ul&gt;<br>      {repos.map(({ name, handle, stars, url }) =&gt; (<br>        &lt;li key={name}&gt;<br>          &lt;ul&gt;<br>            &lt;li&gt;&lt;a href={url}&gt;{name}&lt;/a&gt;&lt;/li&gt;<br>            &lt;li&gt;@{handle}&lt;/li&gt;<br>            &lt;li&gt;{stars} stars&lt;/li&gt;<br>          &lt;/ul&gt;<br>        &lt;/li&gt;<br>      ))}<br>    &lt;/ul&gt;<br>  )<br>}</pre><p><a href="https://codesandbox.io/s/why-react-hooks-useeffect-0m35p"><strong>💻 Play with the code.</strong></a></p><p>Pretty slick, right? We’ve successfully gotten rid of React.Component, constructor, super, this and more importantly, we no longer have our effect logic sprinkled (and duplicated) throughout the component.</p><ul><li>State ✅</li><li>Lifecycle methods ✅</li><li>Sharing non-visual logic</li></ul><h3>Sharing non-visual logic</h3><p>Earlier we mentioned that the reason React didn’t have a great answer to sharing non-visual logic was because “React couples UI to a component”. This lead to overcomplicated patterns like <a href="https://tylermcginnis.com/react-higher-order-components/">Higher-order components</a> or <a href="https://tylermcginnis.com/react-render-props/">Render props</a>. As you can probably guess by now, Hooks have an answer for this too. However, it’s probably not what you think. There’s no built-in Hook for sharing non-visual logic, instead, you can create your own custom Hooks that are decoupled from any UI.</p><p>We can see this in action by creating our own custom useRepos Hook. This Hook will take in an id of the Repos we want to fetch and (to stick to a similar API) will return an array with the first item being the loading state and the second item being the repos state.</p><pre>function useRepos (id) {<br>  const [ repos, setRepos ] = React.useState([])<br>  const [ loading, setLoading ] = React.useState(true)</pre><pre>  React.useEffect(() =&gt; {<br>    setLoading(true)</pre><pre>    fetchRepos(id)<br>      .then((repos) =&gt; {<br>        setRepos(repos)<br>        setLoading(false)<br>      })<br>  }, [id])</pre><pre>  return [ loading, repos ]<br>}</pre><p>What’s nice is any logic that’s related to fetching our repos can be abstracted inside of this custom Hook. Now, regardless of which component we&#39;re in and even though it&#39;s non-visual logic, whenever we need data regarding repos, we can consume our useRepos custom Hook.</p><pre>function ReposGrid ({ id }) {<br>  const [ loading, repos ] = useRepos(id)</pre><pre>  ...<br>}</pre><pre>function Profile ({ user }) {<br>  const [ loading, repos ] = useRepos(user.id)</pre><pre>  ...<br>}</pre><p><a href="https://codesandbox.io/s/why-react-hooks-custom-hooks-t4rqv"><strong>💻 Play with the code.</strong></a></p><ul><li>State ✅</li><li>Lifecycle methods ✅</li><li>Sharing non-visual logic ✅</li></ul><p>The marketing pitch for Hooks is that you’re able to use state inside function components. In reality, Hooks are much more than that. They’re about improved code reuse, composition, and better defaults. There’s a lot more to Hooks we still need to cover, but now that you know WHY they exist, we have a solid foundation to build on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZrJKJqBsksWd-8uKM9OvgA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VJbtw4Cw1h_G4COdDLCKfw.jpeg" /></figure><blockquote>This was originally published at <a href="https://tylermcginnis.com/why-react-hooks/">TylerMcGinnis.com</a> and is part of the <a href="https://tylermcginnis.com/courses/react-hooks/">React Hooks</a> course. If you enjoy this post, check it out.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d72a849a0e6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/dailyjs/why-react-hooks-2d72a849a0e6">Why React Hooks?</a> was originally published in <a href="https://medium.com/dailyjs">DailyJS</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript Inheritance vs Composition]]></title>
            <link>https://medium.com/free-code-camp/javascript-inheritance-vs-composition-ec8ca848b6?source=rss-c52389e3ee63------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec8ca848b6</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Tyler McGinnis]]></dc:creator>
            <pubDate>Wed, 27 Mar 2019 17:51:58 GMT</pubDate>
            <atom:updated>2019-04-01T15:26:31.129Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6H_ppZ4U76KdD-jBs8R8rg.jpeg" /></figure><blockquote><em>This post is designed to be read after you read </em><a href="https://tylermcginnis.com/javascript-inheritance-and-the-prototype-chain/"><strong><em>JavaScript Inheritance and the Prototype Chain</em></strong></a><em>.</em></blockquote><p>If you’d prefer to watch rather than read,</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F7HolHe7Gqbw%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D7HolHe7Gqbw&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F7HolHe7Gqbw%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/427feeff9663bbb57f088614b16a5229/href">https://medium.com/media/427feeff9663bbb57f088614b16a5229/href</a></iframe><p><a href="https://tylermcginnis.com/javascript-inheritance-and-the-prototype-chain/">Previously</a> we looked at how to accomplish inheritance in JavaScript using both ES5 and ES6. In our example, we abstracted the common features amongst every animal (name, energy, eat, sleep, and play) to an Animal base class. Then, whenever we wanted to create an individual type of animal (Dog, Cat, etc.), we created a subclass for that type.</p><pre>class Animal {<br>  constructor(name, energy) {<br>    this.name = name<br>    this.energy = energy<br>  }<br>  eat(amount) {<br>    console.log(`${this.name} is eating.`)<br>    this.energy += amount<br>  }<br>  sleep() {<br>    console.log(`${this.name} is sleeping.`)<br>    this.energy += length<br>  }<br>  play() {<br>    console.log(`${this.name} is playing.`)<br>    this.energy -= length<br>  }<br>}</pre><pre>class Dog extends Animal {<br>  constructor(name, energy, breed) {<br>    super(name, energy)</pre><pre>    this.breed = breed<br>  }<br>  bark() {<br>    console.log(&#39;Woof Woof!&#39;)<br>    this.energy -= .1<br>  }<br>}</pre><pre>class Cat extends Animal {<br>  constructor(name, energy, declawed) {<br>    super(name, energy)</pre><pre>    this.declawed = declawed<br>  }<br>  meow() {<br>    console.log(&#39;Meow!&#39;)<br>    this.energy -= .1<br>  }<br>}</pre><p>And without the code, we can visualize our class structure like this.</p><pre>Animal<br>  name<br>  energy<br>  eat()<br>  sleep()<br>  play()</pre><pre>Dog<br>    breed<br>    bark()</pre><pre>Cat<br>    declawed<br>    meow()</pre><p>This worked well as it allowed us to minimize code duplication and maximize code reuse.</p><p>Let’s take this a step further and pretend we’re building software for “Farm Fantasy” — a massively multiplayer online (MMO) role-playing game where you do the same thing a farmer does, except, you know, online and you pay to do it.</p><p>Now that we’re creating an MMO, we’re going to need to have users. We can update our class structure now to look like this.</p><pre>User<br>  email<br>  username<br>  pets<br>  friends<br>  adopt()<br>  befriend()</pre><pre>Animal<br>  name<br>  energy<br>  eat()<br>  sleep()<br>  play()</pre><pre>Dog<br>    breed<br>    bark()</pre><pre>Cat<br>    declawed<br>    meow()</pre><p>The examples above are textbook examples of classes and inheritance. Sadly, unlike in the classroom, real-world software development isn’t always so predictable.</p><p>Let’s say six months after building out our initial class structure, our project manager decides we need to change some things. Users love the app and the ability to pay to be a pretend farmer, but they want a more real-life experience. Right now, only instances of Animal have the ability to eat, sleep, and play. The users are demanding that they also have those same features.</p><p>Alright, no issue. We just need to adjust our class structure around a little bit.</p><pre>... 🤔</pre><p>I guess we could abstract the common properties to another parent class and have one more step of inheritance.</p><pre>FarmFantasy<br>  name<br>  play()<br>  sleep()<br>  eat()</pre><pre>User<br>    email<br>    username<br>    pets<br>    friends<br>    adopt()<br>    befriend()</pre><pre>Animal<br>    energy</pre><pre>Dog<br>      breed<br>      bark()</pre><pre>Cat<br>      declawed<br>      meow()</pre><p>That works, but it’s incredibly fragile. There’s even a name for this anti-pattern — <a href="https://en.wikipedia.org/wiki/God_object">God object</a>.</p><p>And just like that, we see the most significant weakness with inheritance. With inheritance, you structure your classes around what they <strong>are</strong>, a User, an Animal, a Dog, a Cat - all of those words encapsulate a meaning centered around what those things <strong>are</strong>. The problem with that is a User today will probably be different than a User in 6 months. Inheritance makes us turn a blind eye to the inevitable fact that our class structure will most likely change in the future, and when it does, our tightly coupled inheritance structure is going to crumble.</p><blockquote><em>The problem with object-oriented languages is they’ve got all this implicit environment that they carry around with them. You wanted a banana but what you got was a gorilla holding the banana and the entire jungle. — Joe Armstrong, creator of Erlang.</em></blockquote><p>So if inheritance is such a problem, how do we get the same functionality while minimizing some of the downsides? Rather than thinking in terms of what things <strong>are</strong>, what if we think in terms of what things <strong>do</strong>? Let’s take a Dog, for example. A Dog is a sleeper, eater, player, and barker. A Cat is a sleeper, eater, player, and meower. A User is a sleeper, eater, player, adopter, and friender. Now let’s transform all of these verbs into functions.</p><pre>const eater = () =&gt; ({})<br>const sleeper = () =&gt; ({})<br>const player = () =&gt; ({})<br>const barker = () =&gt; ({})<br>const meower = () =&gt; ({})<br>const adopter = () =&gt; ({})<br>const friender = () =&gt; ({})</pre><p>Do you see where we’re going with this? Instead of having these methods defined (and coupled) to a particular class, if we abstract them into their own functions, we can now compose them together with any type that needs them.</p><p>Let’s take a closer look at one of our methods again, eat.</p><pre>eat(amount) {<br>  console.log(`${this.name} is eating.`)<br>  this.energy += amount<br>}</pre><p>Notice that eat logs to the console then increases the energy property on the instance by the amount argument. Now the question we need to answer is how we can operate on a specific instance from a one-off function? Well, what if we just pass it in when we invoke the function? Seems simple enough.</p><pre>const eater = (state) =&gt; ({<br>  eat(amount) {<br>    console.log(`${state.name} is eating.`)<br>    state.energy += amount<br>  }<br>})</pre><p>Now we can follow this same pattern for each one of our functions.</p><pre>...</pre><pre>const sleeper = (state) =&gt; ({<br>  sleep(length) {<br>    console.log(`${state.name} is sleeping.`)<br>    state.energy += length<br>  }<br>})</pre><pre>const player = (state) =&gt; ({<br>  play() {<br>    console.log(`${state.name} is playing.`)<br>    state.energy -= length<br>  }<br>})</pre><pre>const barker = (state) =&gt; ({<br>  bark() {<br>    console.log(&#39;Woof Woof!&#39;)<br>    state.energy -= .1<br>  }<br>})</pre><pre>const meower = (state) =&gt; ({<br>  meow() {<br>    console.log(&#39;Meow!&#39;)<br>    state.energy -= .1<br>  }<br>})</pre><pre>const adopter = (state) =&gt; ({<br>  adopt(pet) {<br>    state.pets.push(pet)<br>  }<br>})</pre><pre>const friender = (state) =&gt; ({<br>  befriend(friend) {<br>    state.friends.push(friend)<br>  }<br>})</pre><p>Now whenever a Dog, Cat, or User needs to add the ability to do any of the functions above, they merge the object they get from one of the functions onto their own object.</p><p>Let’s see what that looks like. We’ll start with a Dog. Earlier we defined a Dog by what it does, a Dog is a sleeper, eater, player, and barker.</p><pre>function Dog (name, energy, breed) {<br>  let dog = {<br>    name,<br>    energy,<br>    breed,<br>  }</pre><pre>  return Object.assign(<br>    dog,<br>    eater(dog),<br>    sleeper(dog),<br>    player(dog),<br>    barker(dog),<br>  )<br>}</pre><pre>const leo = Dog(&#39;Leo&#39;, 10, &#39;Goldendoodle&#39;)<br>leo.eat(10) // Leo is eating<br>leo.bark() // Woof Woof!</pre><p>Inside of Dog we create the “instance” using a plain old JavaScript object. Then we use Object.assign to merge the dog’s state with all of the methods a dog should have - each defined by what a dog <strong>does</strong>, not what it <strong>is</strong>.</p><p>Now how would we create a Cat class? Earlier we defined a Cat as a sleeper, eater, player, and meower.</p><pre>function Cat (name, energy, declawed) {<br>  let cat = {<br>    name,<br>    energy,<br>    declawed,<br>  }</pre><pre>  return Object.assign(<br>    cat,<br>    eater(cat),<br>    sleeper(cat),<br>    player(cat),<br>    meower(cat),<br>  )<br>}</pre><p>Now, what about a User? Earlier we ran into issues when we needed to refactor our class structure so that users could also sleep, eat, and play. Now that we’ve decoupled our functions from the class hierarchy, this is trivial to do.</p><pre>function User (email, username) {<br>  let user = {<br>    email,<br>    username,<br>    pets: [],<br>    friends: []<br>  }</pre><pre>  return Object.assign(<br>    user,<br>    eater(user),<br>    sleeper(user),<br>    player(user),<br>    adopter(user),<br>    friender(user),<br>  )<br>}</pre><p>To really test our theory, what if we wanted to give all dogs the ability to add friends as well. This wasn’t in our initial requirement but with composition, it’s pretty straight forward.</p><pre>function Dog (name, energy, breed) {<br>  let dog = {<br>    name,<br>    energy,<br>    breed,<br>    friends: []<br>  }</pre><pre>  return Object.assign(<br>    dog,<br>    eater(dog),<br>    sleeper(dog),<br>    player(dog),<br>    barker(dog),<br>    friender(dog),<br>  )<br>}</pre><p>By favoring composition over inheritance and thinking in terms of what things <strong>do</strong> rather than what things <strong>are</strong>, you free yourself of fragile and tightly coupled inheritance structures.</p><p><em>You may have noticed I’m using what we previously referred to as the “Functional Instantiation” pattern. This is mostly for preference since we’re not involving the prototype at all. If for some reason you really liked the this and new keyword, you could use the following pattern.</em></p><pre>function Cat (name, energy, declawed) {<br>  this.name = name<br>  this.energy = energy<br>  this.declawed = declawed</pre><pre>  return Object.assign(<br>    this,<br>    eater(this),<br>    sleeper(this),<br>    player(this),<br>    meower(this),<br>  )<br>}</pre><pre>const charles = new Cat(&#39;Charles&#39;, 10, false)</pre><p><em>This was originally published on </em><a href="https://tylermcginnis.com/javascript-inheritance-vs-composition/"><em>tylermcginnis.com</em></a><em> as part of our </em><a href="https://tylermcginnis.com/courses/advanced-javascript/"><em>Advanced JavaScript</em></a><em> course.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec8ca848b6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/free-code-camp/javascript-inheritance-vs-composition-ec8ca848b6">JavaScript Inheritance vs Composition</a> was originally published in <a href="https://medium.com/free-code-camp">We’ve moved to freeCodeCamp.org/news</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript Modules: From IIFEs to CommonJS to ES6 Modules]]></title>
            <link>https://medium.com/free-code-camp/javascript-modules-from-iifes-to-commonjs-to-es6-modules-4d10c16f55d4?source=rss-c52389e3ee63------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d10c16f55d4</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[modules]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Tyler McGinnis]]></dc:creator>
            <pubDate>Tue, 22 Jan 2019 00:00:00 GMT</pubDate>
            <atom:updated>2019-01-23T11:21:27.114Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2E4DSvdjZfLwjZOcu1_GRg.jpeg" /></figure><p>I’ve taught JavaScript for a long time to a lot of people. Consistently the most commonly under-learned aspect of the language is the module system.</p><p>There’s good reason for that. Modules in JavaScript have a strange and erratic history. In this post we’ll walk through that history and you’ll learn modules of the past to better understand how JavaScript modules work today.</p><p>If you’d rather watch than read, here’s a video that covers the same material. Feel free to <a href="https://www.youtube.com/tylermcginnis?sub_confirmation=1">subscribe</a> 🙂</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FqJWALEoGge4%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DqJWALEoGge4&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FqJWALEoGge4%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/62b4c8bf7306334599e8929fce11d0e4/href">https://medium.com/media/62b4c8bf7306334599e8929fce11d0e4/href</a></iframe><p>Before we learn how to create modules in JavaScript, we first need to understand what they are and why they exist. Look around you right now. Any marginally complex item that you can see is probably built using individual pieces that when put together, form the item.</p><p>Let’s take a watch for example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/0*u4zML75OiXbZum45.jpg" /></figure><p>A simple wristwatch is made up of hundreds of internal pieces. Each has a specific purpose and clear boundaries for how it interacts with the other pieces. Put together, all of these pieces form the whole of the watch. Now I’m no watch engineer, but I think the benefits of this approach are pretty transparent.</p><h4>Reusability</h4><p>Take a look at the diagram above one more time. Notice how many of the same pieces are being used throughout the watch. Through highly intelligent design decisions centered on modularity, they’re able to re-use the same components throughout different aspects of the watch design. This ability to re-use pieces simplifies the manufacturing process and, I’m assuming, increases profit.</p><h4>Composability</h4><p>The diagram is a beautiful illustration of composability. By establishing clear boundaries for each individual component, they’re able to compose each piece together to create a fully functioning watch out of tiny, focused pieces.</p><h4>Leverage</h4><p>Think about the manufacturing process. This company isn’t making watches, it’s making individual components that together form a watch. They could create those pieces in house, they could outsource them and leverage other manufacturing plants, it doesn’t matter. The most important thing is that each pieces comes together in the end to form a watch — where those pieces were created is irrelevant.</p><h4>Isolation</h4><p>Understanding the whole system is difficult. Because the watch is composed of small, focused pieces, each of those pieces can be thought about, built and or repaired in isolation. This isolation allows multiple people to work individually on the watch while not bottle-necking each other. Also if one of the pieces breaks, instead of replacing the whole watch, you just have to replace the individual piece that broke.</p><h4>Organization</h4><p>Organization is a byproduct of each individual piece having a clear boundary for how it interacts with other pieces. With this modularity, organization naturally occurs without much thought.</p><p>We’ve seen the obvious benefits of modularity when it comes to every day items like a watch, but what about software? Turns out, it’s the same idea with the same benefits. Just how the watch was designed, we <em>should</em> design our software separated into different pieces where each piece has a specific purpose and clear boundaries for how it interacts with other pieces. In software, these pieces are called <strong>modules</strong>. At this point a module might not sound too different from something like a function or a React component. So what exactly would a module encompass?</p><p>Each module has three parts — dependencies (also called imports), code, and exports.</p><pre>imports</pre><pre>code</pre><pre>exports</pre><p><strong>Dependencies (Imports)<br></strong>When one module needs another module, it can import that module as a dependency. For example, whenever you want to create a React component, you need to import the react module. If you want to use a library like lodash, you’d need import the lodash module.</p><p><strong>Code<br></strong>After you’ve established what dependencies your module needs, the next part is the actual code of the module.</p><p><strong>Exports<br></strong>Exports are the “interface” to the module. Whatever you export from a module will be available to whoever imports that module.</p><h3>Real-World Examples</h3><p>Enough with the high level stuff, let’s dive into some real examples.</p><p>First, let’s look at React Router. Conveniently, they have a <a href="https://github.com/ReactTraining/react-router/tree/master/packages/react-router/modules">modules</a> folder. This folder is filled with… modules, naturally.</p><p>So in React Router, what makes a “module”? Turns out, for the most part, they map their React components directly to modules.</p><p>That makes sense and in general is how you separate components in a React project. This works because if you re-read the watch above but swap out “module” with “component”, the metaphors still make sense.</p><p>Let’s look at the code from the MemoryRouter module. Don’t worry about the actual code for now, but focus on more of the structure of the module.</p><pre>// imports<br>import React from &quot;react&quot;;<br>import { createMemoryHistory } from &quot;history&quot;;<br>import Router from &quot;./Router&quot;;</pre><pre>// code<br>class MemoryRouter extends React.Component {<br>  history = createMemoryHistory(this.props);<br>  render() {<br>    return (<br>      &lt;Router<br>        history={this.history}<br>        children={this.props.children}<br>      /&gt;;<br>    )<br>  }<br>}</pre><pre>// exports<br>export default MemoryRouter;</pre><p>You’ll notice at the top of the module they define their imports, or what other modules they need to make the MemoryRouter module work properly. Next, they have their code. In this case they create a new React component called MemoryRouter. Then at the very bottom they define their export, MemoryRouter. This means that whenever someone imports the MemoryRouter module, they’ll get the MemoryRouter component.</p><p>Now that we understand what a module is, let’s look back at the benefits of the watch design and see how, by following a similar modular architecture, those same benefits can apply to software design.</p><h4>Reusability</h4><p>Modules maximize reusability since a module can be imported and used in any other module that needs it. Beyond this, if a module would be beneficial in another program, you can create a package out of it. A package can contain one or more modules and can be uploaded to <a href="http://npmjs.com/">NPM</a> to be downloaded by anyone. react, lodash, and jquery are all examples of NPM packages since they can be installed from the NPM directory.</p><h4>Composability</h4><p>Because modules explicitly define their imports and exports, they can be easily composed. More than that, a sign of good software is that is can be easily deleted. Modules increases the “delete-ability” of your code.</p><h4>Leverage</h4><p>The NPM registry hosts the world’s largest collection of free, reusable modules (over 700,000 to be exact). Odds are if you need a specific package, NPM has it.</p><h4>Isolation</h4><p>The text we used to describe isolation of the watch fits perfectly here as well. “Understanding the whole system is difficult. Because (your software) is composed of small, focused (modules), each of those (modules) can be thought about, built and or repaired in isolation. This isolation allows multiple people to work individually on the (app) while not bottle-necking each other. Also if one of the (modules) breaks, instead of replacing the whole (app), you just have to replace the individual (module) that broke.”</p><h4>Organization</h4><p>Perhaps the biggest benefit in regards to modular software is organization. Modules provide a natural separation point. Along with that, as we’ll see soon, modules prevent you from polluting the global namespace and allow you to avoid naming collisions.</p><h3>Let’s Get Building</h3><p>At this point you know the benefits and understand the structure of modules. Now it’s time to actually start building them. Our approach to this will be pretty methodical. The reason for that is because, as mentioned earlier, modules in JavaScript have a strange history. Even though there are “newer” ways to create modules in JavaScript, some of the older flavors still exist and you’ll see them from time to time. If we jump straight to modules in 2018, I’d be doing you a disservice. With that said, we’re going to take it back to late 2010. AngularJS was just released and jQuery is all the rage. Companies are finally using JavaScript to build complex web applications and with that complexity comes a need to manage it — via modules.</p><p>Your first intuition for creating modules may be to separate code by files.</p><pre>// users.js<br>var users = [&quot;Tyler&quot;, &quot;Sarah&quot;, &quot;Dan&quot;]</pre><pre>function getUsers() {<br>  return users<br>}</pre><pre><br>// dom.js<br>function addUserToDOM(name) {<br>  const node = document.createElement(&quot;li&quot;)<br>  const text = document.createTextNode(name)<br>  node.appendChild(text)</pre><pre>  document.getElementById(&quot;users&quot;)<br>    .appendChild(node)<br>}</pre><pre>document.getElementById(&quot;submit&quot;)<br>  .addEventListener(&quot;click&quot;, function() {<br>    var input = document.getElementById(&quot;input&quot;)<br>    addUserToDOM(input.value)</pre><pre>    input.value = &quot;&quot;<br>  })</pre><pre>var users = window.getUsers()</pre><pre>for (var i = 0; i &lt; users.length; i++) {<br>  addUserToDOM(users[i])<br>}</pre><pre><br>&lt;!-- index.html --&gt;<br>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>  &lt;head&gt;<br>    &lt;title&gt;Users&lt;/title&gt;<br>  &lt;/head&gt;</pre><pre>  &lt;body&gt;<br>    &lt;h1&gt;Users&lt;/h1&gt;<br>    &lt;ul id=&quot;users&quot;&gt;&lt;/ul&gt;<br>    &lt;input<br>      id=&quot;input&quot;<br>      type=&quot;text&quot;<br>      placeholder=&quot;New User&quot;&gt;<br>    &lt;/input&gt;<br>    &lt;button id=&quot;submit&quot;&gt;Submit&lt;/button&gt;</pre><pre>    &lt;script src=&quot;users.js&quot;&gt;&lt;/script&gt;<br>    &lt;script src=&quot;dom.js&quot;&gt;&lt;/script&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><blockquote><strong><em>The full code can be found </em></strong><a href="https://github.com/tylermcginnis/modules/tree/separate-files"><strong><em>here</em></strong></a><em>.</em></blockquote><p>OK. We’ve successfully separated our app into its own files. Does that means we’ve successfully implemented modules? No. Absolutely not. Literally all we’ve done is separate where the code lives.</p><p>The only way to create a new scope in JavaScript is with a function. All the variables we declared that aren’t in a function are just living on the global object. You can see this by logging the window object in the console. You’ll notice we can access, and worse, change addUsers, users, getUsers, addUserToDOM.</p><p>That’s essentially our entire app. We’ve done nothing to separate our code into modules, all we’ve done is separate it by physical location. If you’re new to JavaScript, this may be a surprise to you but it was probably your first intuition for how to implement modules in JavaScript.</p><p>So if file separation doesn’t give us modules, what does? Remember the advantages to modules — reusability, composability, leverage, isolation, organization. Is there a native feature of JavaScript we could use to create our own “modules” that would give us the same benefits? What about a regular old function? When you think of the benefits of a function, they align nicely to the benefits of modules. So how would this work? What if instead of having our entire app live in the global namespace, we instead expose a single object, we’ll call it APP.</p><p>We can then put all the methods our app needs to run under the APP, which will prevent us from polluting the global namespace. We could then wrap everything else in a function to keep it enclosed from the rest of the app.</p><pre>// App.js<br>var APP = {}</pre><pre>// users.js<br>function usersWrapper () {<br>  var users = [&quot;Tyler&quot;, &quot;Sarah&quot;, &quot;Dan&quot;]</pre><pre>  function getUsers() {<br>    return users<br>  }</pre><pre>  APP.getUsers = getUsers<br>}</pre><pre>usersWrapper()</pre><pre>// dom.js<br>function domWrapper() {<br>  function addUserToDOM(name) {<br>    const node = document.createElement(&quot;li&quot;)<br>    const text = document.createTextNode(name)<br>    node.appendChild(text)</pre><pre>    document.getElementById(&quot;users&quot;)<br>      .appendChild(node)<br>  }</pre><pre>  document.getElementById(&quot;submit&quot;)<br>    .addEventListener(&quot;click&quot;, function() {<br>      var input = document.getElementById(&quot;input&quot;)<br>      addUserToDOM(input.value)</pre><pre>      input.value = &quot;&quot;<br>  })</pre><pre>  var users = APP.getUsers()<br>  for (var i = 0; i &lt; users.length; i++) {<br>    addUserToDOM(users[i])<br>  }<br>}</pre><pre>domWrapper()</pre><pre>&lt;!-- index.html --&gt;<br>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>  &lt;head&gt;<br>    &lt;title&gt;Users&lt;/title&gt;<br>  &lt;/head&gt;</pre><pre>  &lt;body&gt;<br>    &lt;h1&gt;Users&lt;/h1&gt;<br>    &lt;ul id=&quot;users&quot;&gt;&lt;/ul&gt;<br>    &lt;input<br>      id=&quot;input&quot;<br>      type=&quot;text&quot;<br>      placeholder=&quot;New User&quot;&gt;<br>    &lt;/input&gt;<br>    &lt;button id=&quot;submit&quot;&gt;Submit&lt;/button&gt;</pre><pre>    &lt;script src=&quot;app.js&quot;&gt;&lt;/script&gt;<br>    &lt;script src=&quot;users.js&quot;&gt;&lt;/script&gt;<br>    &lt;script src=&quot;dom.js&quot;&gt;&lt;/script&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><blockquote><strong><em>The full code can be found </em></strong><a href="https://github.com/tylermcginnis/modules/tree/wrappers"><strong><em>here</em></strong></a><em>.</em></blockquote><p>Now if you look at the window object, instead of it having all the important pieces of our app, it just has APP and our wrapper functions, usersWrapper and domWrapper. More important, none of our important code (like users) can be modified since they’re no longer on the global namespace.</p><p>Let’s see if we can take this a step further. Is there a way to get rid of our wrapper functions? Notice that we’re defining and then immediately invoking them. The only reason we gave them a name was so we could immediately invoke them. Is there a way to immediately invoke an anonymous function so we wouldn’t have to give them a name? Turns out there is and it even has a fancy name — Immediately Invoked Function Expression or IIFE for short.</p><h3>IIFE</h3><p>Here’s what it looks like.</p><pre>(function () {<br>  console.log(&#39;Pronounced IF-EE&#39;)<br>})()</pre><p>Notice it’s just an anonymous function expression that we’ve wrapped in parens ().</p><pre>(function () {<br>  console.log(&#39;Pronounced IF-EE&#39;)<br>})</pre><p>Then, just like any other function, in order to invoke it, we add another pair of parens to the end of it.</p><pre>(function () {<br>  console.log(&#39;Pronounced IF-EE&#39;)<br>})()</pre><p>Now let’s use our knowledge of IIFEs in order to get rid of our ugly wrapper functions and clean up the global namespace even more.</p><pre>// users.js<br>(function () {<br>  var users = [&quot;Tyler&quot;, &quot;Sarah&quot;, &quot;Dan&quot;]</pre><pre>  function getUsers() {<br>    return users<br>  }</pre><pre>  APP.getUsers = getUsers<br>})()<br></pre><pre>// dom.js<br>(function () {<br>  function addUserToDOM(name) {<br>    const node = document.createElement(&quot;li&quot;)<br>    const text = document.createTextNode(name)<br>    node.appendChild(text)</pre><pre>    document.getElementById(&quot;users&quot;)<br>      .appendChild(node)<br>  }</pre><pre>  document.getElementById(&quot;submit&quot;)<br>    .addEventListener(&quot;click&quot;, function() {<br>      var input = document.getElementById(&quot;input&quot;)<br>      addUserToDOM(input.value)</pre><pre>      input.value = &quot;&quot;<br>  })</pre><pre>  var users = APP.getUsers()<br>  for (var i = 0; i &lt; users.length; i++) {<br>    addUserToDOM(users[i])<br>  }<br>})()</pre><blockquote><strong><em>The full code can be found </em></strong><a href="https://github.com/tylermcginnis/modules/tree/IIFEs"><strong><em>here</em></strong></a><em>.</em></blockquote><p><strong><em>chef’s kiss</em></strong>. Now if you look at the window object, you’ll notice the only thing we’ve added to it is APP, which we use as a namespace for all the methods our app needs to properly run.</p><p>Let’s call this pattern the <strong>IIFE Module Pattern</strong>.</p><p>What are the benefits to the IIFE Module Pattern? First and foremost, we avoid dumping everything onto the global namespace. This will help with variable collisions and keeps our code more private. Does it have any downsides? It sure does. We still have 1 item on the global namespace, APP. If by chance another library uses that same namespace, we’re in trouble. Second, you’ll notice the order of the &lt;script&gt; tags in our index.html file matter. If you don’t have the scripts in the exact order they are now, the app will break.</p><p>Even though our solution isn’t perfect, we’re making progress. Now that we understand the pros and cons to the IIFE module pattern, if we were to make our own standard for creating and managing modules, what features would it have?</p><p>Earlier our first instinct for the separation of modules was to have a new module for each file. Even though that doesn’t work out of the box with JavaScript, I think that’s an obvious separation point for our modules. <strong>Each file is its own module.</strong> Then from there the only other feature we’d need is to have each file define <strong>explicit imports</strong> (or dependencies) and <strong>explicit exports</strong> which will be available to any other file that imports the module.</p><pre>Our Module Standard</pre><pre>1) File based<br>2) Explicit imports<br>3) Explicit exports</pre><p>Now that we know the features our module standard will need, let’s dive into the API. The only real API we need to define is what imports and exports look like. Let’s start with exports. To keep things simple, any information regarding the module can go on the module object. Then, anything we want to export from a module we can stick on module.exports. Something like this</p><pre>var users = [&quot;Tyler&quot;, &quot;Sarah&quot;, &quot;Dan&quot;]</pre><pre>function getUsers() {<br>  return users<br>}</pre><pre>module.exports.getUsers = getUsers</pre><p>This means another way we can write it is like this</p><pre>var users = [&quot;Tyler&quot;, &quot;Sarah&quot;, &quot;Dan&quot;]</pre><pre>function getUsers() {<br>  return users<br>}</pre><pre>module.exports = {<br>  getUsers: getUsers<br>}</pre><p>Regardless of how many methods we had, we could just add them to the exports object.</p><pre>// users.js</pre><pre>var users = [&quot;Tyler&quot;, &quot;Sarah&quot;, &quot;Dan&quot;]</pre><pre>module.exports = {<br>  getUsers: function () {<br>    return users<br>  },<br>  sortUsers: function () {<br>    return users.sort()<br>  },<br>  firstUser: function () {<br>    return users[0]<br>  }<br>}</pre><p>Now that we’ve figured out what exporting from a module looks like, we need to figure out what the API for importing modules looks like. To keep this one simple as well, let’s pretend we had a function called require. It’ll take a string path as its first argument and will return whatever is being exported from that path. Going along with our users.js file above, to import that module would look something like this</p><pre>var users = require(&#39;./users&#39;)</pre><pre>users.getUsers() // [&quot;Tyler&quot;, &quot;Sarah&quot;, &quot;Dan&quot;]<br>users.sortUsers() // [&quot;Dan&quot;, &quot;Sarah&quot;, &quot;Tyler&quot;]<br>users.firstUser() // [&quot;Tyler&quot;]</pre><p>Pretty slick. With our hypothetical module.exports and require syntax, we’ve kept all of the benefits of modules while getting rid of the two downsides to our IIFE Modules pattern.</p><p>As you probably guessed by now, this isn’t a made up standard. It’s real and it’s called CommonJS.</p><blockquote><em>The CommonJS group defined a module format to solve JavaScript scope issues by making sure each module is executed in its own namespace. This is achieved by forcing modules to explicitly export those variables it wants to expose to the “universe”, and also by defining those other modules required to properly work.</em></blockquote><blockquote><em>- Webpack docs</em></blockquote><p>If you’ve used Node before, CommonJS should look familiar. The reason for that is because Node uses (for the most part) the CommonJS specification in order to implement modules. So with Node you get modules out of the box using the CommonJS require and module.exports syntax you saw earlier. However, unlike Node, browsers don’t support CommonJS. In fact, not only do browsers not support CommonJS, but out of the box, CommonJS isn’t a great solution for browsers since it loads modules synchronously. In the land of the browser, the asynchronous loader is king.</p><p>So in summary, there are two problems with CommonJS. First, the browser doesn’t understand it. Second, it loads modules synchronously which in the browser would be a terrible user experience. If we can fix those two problems, we’re in good shape. So what’s the point of spending all this time talking about CommonJS if it’s not even good for browsers? Well there is a solution and it’s called a module bundler.</p><h3>Module Bundlers</h3><p>What a JavaScript module bundler does is it examines your codebase, looks at all the imports and exports, then intelligently bundles all of your modules together into a single file that the browser can understand. Then instead of including all the scripts in your index.html file and worrying about what order they go in, you include the single bundle.js file the bundler creates for you.</p><pre>app.js ---&gt; |         |<br>users.js -&gt; | Bundler | -&gt; bundle.js<br>dom.js ---&gt; |         |</pre><p>So how does a bundler actually work? That’s a really big question and one I don’t fully understand myself, but here’s the output after running our simple code through <a href="https://webpack.js.org/">Webpack</a>, a popular module bundler.</p><blockquote><strong><em>The full code can with CommonJS and Webpack can be found </em></strong><a href="https://github.com/tylermcginnis/modules/tree/commonjs"><strong><em>here</em></strong></a><em>. You’ll need to download the code, run “npm install”, then run “webpack”.</em></blockquote><pre>(function(modules) { // webpackBootstrap<br>  // The module cache<br>  var installedModules = {};<br>  // The require function<br>  function __webpack_require__(moduleId) {<br>    // Check if module is in cache<br>    if(installedModules[moduleId]) {<br>      return installedModules[moduleId].exports;<br>    }<br>    // Create a new module (and put it into the cache)<br>    var module = installedModules[moduleId] = {<br>      i: moduleId,<br>      l: false,<br>      exports: {}<br>    };<br>    // Execute the module function<br>    modules[moduleId].call(<br>      module.exports,<br>      module,<br>      module.exports,<br>      __webpack_require__<br>    );<br>    // Flag the module as loaded<br>    module.l = true;<br>    // Return the exports of the module<br>    return module.exports;<br>  }<br>  // expose the modules object (__webpack_modules__)<br>  __webpack_require__.m = modules;<br>  // expose the module cache<br>  __webpack_require__.c = installedModules;<br>  // define getter function for harmony exports<br>  __webpack_require__.d = function(exports, name, getter) {<br>    if(!__webpack_require__.o(exports, name)) {<br>      Object.defineProperty(<br>        exports,<br>        name,<br>        { enumerable: true, get: getter }<br>      );<br>    }<br>  };<br>  // define __esModule on exports<br>  __webpack_require__.r = function(exports) {<br>    if(typeof Symbol !== &#39;undefined&#39; &amp;&amp; Symbol.toStringTag) {<br>      Object.defineProperty(exports, Symbol.toStringTag, { value: &#39;Module&#39; });<br>    }<br>    Object.defineProperty(exports, &#39;__esModule&#39;, { value: true });<br>  };<br>  // create a fake namespace object<br>  // mode &amp; 1: value is a module id, require it<br>  // mode &amp; 2: merge all properties of value into the ns<br>  // mode &amp; 4: return value when already ns object<br>  // mode &amp; 8|1: behave like require<br>  __webpack_require__.t = function(value, mode) {<br>    if(mode &amp; 1) value = __webpack_require__(value);<br>    if(mode &amp; 8) return value;<br>    if((mode &amp; 4) &amp;&amp; typeof value === &#39;object&#39; &amp;&amp; value &amp;&amp; value.__esModule) return value;<br>    var ns = Object.create(null);<br>    __webpack_require__.r(ns);<br>    Object.defineProperty(ns, &#39;default&#39;, { enumerable: true, value: value });<br>    if(mode &amp; 2 &amp;&amp; typeof value != &#39;string&#39;)<br>      for(var key in value)<br>        __webpack_require__.d(ns, key, function(key) {<br>          return value[key];<br>        }.bind(null, key));<br>    return ns;<br>  };<br>  // getDefaultExport function for compatibility with non-harmony modules<br>  __webpack_require__.n = function(module) {<br>    var getter = module &amp;&amp; module.__esModule ?<br>      function getDefault() { return module[&#39;default&#39;]; } :<br>      function getModuleExports() { return module; };<br>    __webpack_require__.d(getter, &#39;a&#39;, getter);<br>    return getter;<br>  };<br>  // Object.prototype.hasOwnProperty.call<br>  __webpack_require__.o = function(object, property) {<br>      return Object.prototype.hasOwnProperty.call(object, property);<br>  };<br>  // __webpack_public_path__<br>  __webpack_require__.p = &quot;&quot;;<br>  // Load entry module and return exports<br>  return __webpack_require__(__webpack_require__.s = &quot;./dom.js&quot;);<br>})<br>/************************************************************************/<br>({</pre><pre>/***/ &quot;./dom.js&quot;:<br>/*!****************!*\<br>  !*** ./dom.js ***!<br>  \****************/<br>/*! no static exports found */<br>/***/ (function(module, exports, __webpack_require__) {</pre><pre>eval(`<br>  var getUsers = __webpack_require__(/*! ./users */ \&quot;./users.js\&quot;).getUsers\n\n<br>  function addUserToDOM(name) {\n<br>    const node = document.createElement(\&quot;li\&quot;)\n<br>    const text = document.createTextNode(name)\n<br>    node.appendChild(text)\n\n<br>    document.getElementById(\&quot;users\&quot;)\n<br>      .appendChild(node)\n}\n\n<br>    document.getElementById(\&quot;submit\&quot;)\n<br>      .addEventListener(\&quot;click\&quot;, function() {\n<br>        var input = document.getElementById(\&quot;input\&quot;)\n<br>        addUserToDOM(input.value)\n\n<br>        input.value = \&quot;\&quot;\n})\n\n<br>        var users = getUsers()\n<br>        for (var i = 0; i &lt; users.length; i++) {\n<br>          addUserToDOM(users[i])\n<br>        }\n\n\n//# sourceURL=webpack:///./dom.js?`<br>);}),</pre><pre>/***/ &quot;./users.js&quot;:<br>/*!******************!*\<br>  !*** ./users.js ***!<br>  \******************/<br>/*! no static exports found */<br>/***/ (function(module, exports) {</pre><pre>eval(`<br>  var users = [\&quot;Tyler\&quot;, \&quot;Sarah\&quot;, \&quot;Dan\&quot;]\n\n<br>  function getUsers() {\n<br>    return users\n}\n\nmodule.exports = {\n<br>      getUsers: getUsers\n<br>    }\n\n//# sourceURL=webpack:///./users.js?`);})<br>});</pre><p>You’ll notice that there’s a lot of magic going on there (you can read the comments if you want to know exactly what’s happening), but one thing that’s interesting is they wrap all the code inside of a big IIFE. So they’ve figured out a way to get all of the benefits of a nice module system without the downsides, simply by utilizing our old IIFE Module Pattern.</p><h3>JavaScript Standards</h3><p>What really future proofs JavaScript is that it’s a living language. TC-39, the standards committee around JavaScript, meets a few times a year to discuss potential improvements to the language. At this point, it should be pretty clear that modules are a critical feature for writing scalable, maintainable JavaScript. In ~2013 (and probably long before) it was dead obvious that JavaScript needed a standardized, built in solution for handling modules. This kicked off the process for implementing modules natively into JavaScript.</p><p>Knowing what you know now, if you were tasked with creating a module system for JavaScript, what would it look like? CommonJS got it mostly right. Like CommonJS, each file could be a new module with a clear way to define imports and exports — obviously, that’s the whole point. A problem we ran into with CommonJS is it loads modules synchronously. That’s great for the server but not for the browser. One change we could make would be to support asynchronous loading. Another change we could make is rather than a require function call, since we’re talking about adding to the language itself, we could define new keywords. Let’s go with import and export.</p><p>Without going too far down the “hypothetical, made up standard” road again, the TC-39 committee came up with these exact same design decisions when they created “ES Modules”, now the standardized way to create modules in JavaScript. Let’s take a look at the syntax.</p><h3>ES Modules</h3><p>As mentioned above, in order to specify what should be exported from a module you use the export keyword.</p><pre>// utils.js</pre><pre>// Not exported<br>function once(fn, context) {<br> var result<br> return function() {<br>  if(fn) {<br>   result = fn.apply(context || this, arguments)<br>   fn = null<br>  }<br>  return result<br> }<br>}</pre><pre>// Exported<br>export function first (arr) {<br>  return arr[0]<br>}</pre><pre>// Exported<br>export function last (arr) {<br>  return arr[arr.length - 1]<br>}</pre><p>Now in order to import first and last, you have a few different options. One is to import everything that is being exported from utils.js.</p><pre>import * as utils from &#39;./utils&#39;</pre><pre>utils.first([1,2,3]) // 1<br>utils.last([1,2,3]) // 3</pre><p>But what if we didn’t want to import everything the module is exporting? In this example, what if we wanted to import first but not last? This is where you can use what’s called named imports (it looks like <a href="https://tylermcginnis.com/object-array-destructuring/">destructuring</a> but it’s not).</p><pre>import { first } from &#39;./utils&#39;</pre><pre>first([1,2,3]) // 1</pre><p>What’s cool about ES Modules is not only can you specify multiple exports, but you can also specify a default export.</p><pre>// leftpad.js</pre><pre>export default function leftpad (str, len, ch) {<br>  var pad = &#39;&#39;;<br>  while (true) {<br>    if (len &amp; 1) pad += ch;<br>    len &gt;&gt;= 1;<br>    else break;<br>  }<br>  return pad + str;<br>}</pre><p>When you use a default export, that changes how you import that module. Instead of using the * syntax or using named imports, you just use import name from &#39;./path&#39;.</p><pre>import leftpad from &#39;./leftpad&#39;</pre><p>Now, what if you had a module that was exporting a default export but also other regular exports as well? Well, you’d do it how you’d expect.</p><pre>// utils.js</pre><pre>function once(fn, context) {<br> var result<br> return function() {<br>  if(fn) {<br>   result = fn.apply(context || this, arguments)<br>   fn = null<br>  }<br>  return result<br> }<br>}</pre><pre>// regular export<br>export function first (arr) {<br>  return arr[0]<br>}</pre><pre>// regular export<br>export function last (arr) {<br>  return arr[arr.length - 1]<br>}</pre><pre>// default export<br>export default function leftpad (str, len, ch) {<br>  var pad = &#39;&#39;;<br>  while (true) {<br>    if (len &amp; 1) pad += ch;<br>    len &gt;&gt;= 1;<br>    else break;<br>  }<br>  return pad + str;<br>}</pre><p>Now what would the import syntax look like? In this case, again, it should be what you expect.</p><pre>import leftpad, { first, last } from &#39;./utils&#39;</pre><p>Pretty slick, yeah? leftpad is the default export and first and last are just the regular exports.</p><p>What’s interesting about ES Modules is, because they’re now native to JavaScript, modern browsers support them without using a bundler. Let’s look back at our simple Users example from the beginning of this tutorial and see what it would look like with ES Modules.</p><blockquote><strong><em>The full code can be found </em></strong><a href="https://github.com/tylermcginnis/modules/tree/esModules"><strong><em>here</em></strong></a><em>.</em></blockquote><pre>// users.js<br>var users = [&quot;Tyler&quot;, &quot;Sarah&quot;, &quot;Dan&quot;]</pre><pre>export default function getUsers() {<br>  return users<br>}</pre><pre>// dom.js<br>import getUsers from &#39;./users.js&#39;</pre><pre>function addUserToDOM(name) {<br>  const node = document.createElement(&quot;li&quot;)<br>  const text = document.createTextNode(name)<br>  node.appendChild(text)</pre><pre>document.getElementById(&quot;users&quot;)<br>    .appendChild(node)<br>}</pre><pre>document.getElementById(&quot;submit&quot;)<br>  .addEventListener(&quot;click&quot;, function() {<br>    var input = document.getElementById(&quot;input&quot;)<br>    addUserToDOM(input.value)</pre><pre>input.value = &quot;&quot;<br>})</pre><pre>var users = getUsers()<br>for (var i = 0; i &lt; users.length; i++) {<br>  addUserToDOM(users[i])<br>}</pre><p>Now here’s the cool part. With our IIFE pattern, we still needed to include a script to every JS file (and in order, none the less). With CommonJS we needed to use a bundler like Webpack and then include a script to the bundle.js file. With ES Modules, in <a href="https://caniuse.com/#feat=es6-modulef">modern browsers</a>, all we need to do is include our main file (in this case dom.js) and add a type=&#39;module&#39; attribute to the script tab.</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>  &lt;head&gt;<br>    &lt;title&gt;Users&lt;/title&gt;<br>  &lt;/head&gt;</pre><pre>  &lt;body&gt;<br>    &lt;h1&gt;Users&lt;/h1&gt;<br>    &lt;ul id=&quot;users&quot;&gt;<br>    &lt;/ul&gt;<br>    &lt;input id=&quot;input&quot; type=&quot;text&quot; placeholder=&quot;New User&quot;&gt;&lt;/input&gt;<br>    &lt;button id=&quot;submit&quot;&gt;Submit&lt;/button&gt;</pre><pre>  &lt;script type=module src=&#39;dom.js&#39;&gt;&lt;/script&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><h3>Tree Shaking</h3><p>There’s one more difference between CommonJS modules and ES Modules that we didn’t cover above.</p><p>With CommonJS, you can require a module anywhere, even conditionally.</p><pre>if (pastTheFold === true) {<br>  require(&#39;./parallax&#39;)<br>}</pre><p>Because ES Modules are static, import statements must always be at the top level of a module. You can’t conditionally import them.</p><pre>if (pastTheFold === true) {<br>  import &#39;./parallax&#39; // &quot;import&#39; and &#39;export&#39; may only appear at the top level&quot;<br>}</pre><p>The reason this design decision was made was because by forcing modules to be static, the loader can statically analyze the module tree, figure out which code is actually being used, and drop the unused code from your bundle. That was a lot of big words. Said differently, because ES Modules force you to declare your import statements at the top of your module, the bundler can quickly understand your dependency tree. When it understands your dependency tree, it can see what code isn’t being used and drop it from the bundle. This is called <a href="https://webpack.js.org/guides/tree-shaking/">Tree Shaking or Dead Code Elimination</a>.</p><blockquote><em>There is a stage 3 proposal for </em><a href="https://tylermcginnis.com/react-router-code-splitting/"><em>dynamic imports</em></a><em> which will allow you to conditionally load modules via import().</em></blockquote><p>I hope diving into the history of JavaScript modules has helped you gain not only a better appreciation for ES Modules, but also a better understanding of their design decisions.</p><p>I originally published this at <a href="https://tylermcginnis.com/javascript-modules-iifes-commonjs-esmodules/">tylermcginnis.com</a> as part of our <a href="http://tylermcginnis.com/courses/advanced-javascript/">Advanced JavaScript</a> course<em>. </em><strong>If you enjoyed this post, you can </strong><a href="http://twitter.com/tylermcginnis"><strong>follow me on Twitter</strong></a><strong> or </strong><a href="https://www.youtube.com/tylermcginnis?sub_confirmation=1"><strong>subscribe to our YouTube channel</strong></a><strong>.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d10c16f55d4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/free-code-camp/javascript-modules-from-iifes-to-commonjs-to-es6-modules-4d10c16f55d4">JavaScript Modules: From IIFEs to CommonJS to ES6 Modules</a> was originally published in <a href="https://medium.com/free-code-camp">We’ve moved to freeCodeCamp.org/news</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Recursive paths with React Router]]></title>
            <link>https://medium.com/swlh/recursive-paths-with-react-router-3ebddae98f68?source=rss-c52389e3ee63------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ebddae98f68</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-router]]></category>
            <dc:creator><![CDATA[Tyler McGinnis]]></dc:creator>
            <pubDate>Thu, 03 Jan 2019 17:30:51 GMT</pubDate>
            <atom:updated>2019-01-08T06:27:13.889Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P5L0AT5R-AyY3juji5j2jw.jpeg" /></figure><p>Because React Router is just components, you can do crazy things like having recursive routes. In this post we’ll learn how they work by breaking down the ‘Recursive Paths’ example on the React Router docs.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fgb74jqcPN_Q%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dgb74jqcPN_Q&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fgb74jqcPN_Q%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/43f0b30bc50d5802636457ed0ad29f90/href">https://medium.com/media/43f0b30bc50d5802636457ed0ad29f90/href</a></iframe><p>Recursive routes aren’t the most pragmatic thing in the world, but they really show off the benefits of React Router’s component based approach to routing.</p><p>The main idea here is that since React Router is just components, theoretically, you can create recursive and therefor infinite routes. The secret lies in setting up the right data structure which can lead to infinite routes. In this example we’ll use an array of people who all have an id, a name, and an array of friends.</p><pre>const users = [<br>  { id: 0, name: &#39;Michelle&#39;, friends: [ 1, 2, 3 ] },<br>  { id: 1, name: &#39;Sean&#39;, friends: [ 0, 3 ] },<br>  { id: 2, name: &#39;Kim&#39;, friends: [ 0, 1, 3 ], },<br>  { id: 3, name: &#39;David&#39;, friends: [ 1, 2 ] }<br>]</pre><p>By having this data structure set up this way, when we render a Person, we’ll render all of their friends as Links. Then, when a Link is clicked, we’ll render all of that person’s friends as Links, and on and on. Each time a Link is clicked, the app’s pathname will become progressively longer.</p><p>Initially, we’ll be at / and the UI will look like this</p><pre>Michelle&#39;s Friends</pre><pre>* Sean<br>  * Kim<br>  * David</pre><p>If Kim is clicked, then the URL will change to /2 (Kim’s ID) and the UI will look like this</p><pre>Michelle&#39;s Friends</pre><pre>* Sean<br>  * Kim<br>  * David</pre><pre>Kim&#39;s Friends</pre><pre>* Michelle<br>  * Sean<br>  * David</pre><p>If David is clicked, then the URL will change to /2/3 (Kim’s id then David’s id) and the UI will look like this</p><pre>Michelle&#39;s Friends</pre><pre>* Sean<br>  * Kim<br>  * David</pre><pre>Kim&#39;s Friends</pre><pre>* Michelle<br>  * Sean<br>  * David</pre><pre>David&#39;s Friends</pre><pre>* Sean<br>  * Kim</pre><p>And this process repeats for as long as the user wants to click on Links.</p><p>Once you have the right data structure set up, the next important step is to continually render a Route and some Linkss. Because we’re creating infinite routes, we’ll need to make sure we have a Route that is rendered every time a Link is clicked. If not, we won’t get any more matches which means React Router won’t render any more components. In both our Link and our Route we’ll need to know the app’s current pathname so that we can append to it every time a Link is clicked (like in the example above, we went from /2 to /2/3, and on). Luckily for us, React Router gives us the pathname with match.url. With that in mind, the initial part of our Link will look like this</p><pre>&lt;Link to={`{match.url}/${id}}&gt;</pre><p>and the Route we render will match on a similar pattern then render the same component.</p><pre>&lt;Route path={`${match.url}/:id`} component={Person}/&gt;</pre><p>Now that we have the basics down, let’s start building out the component which is going to be recursively rendered, Person.</p><p>Remember, there’s a few things this component needs to be responsible for.</p><ol><li>It should render a Link component for every one of that specific person’s friends.</li><li>It should render a Route component which will match for the current pathname + /:id.</li></ol><p>As with all recursive problems, we need to somehow “kick off” the recursion. Typically this involves invoking the function but if it’s a component that’s being called recursively, we can do that by simply creating the element.</p><pre>import React from &#39;react&#39;<br>import {<br>  BrowserRouter as Router,<br>  Route,<br>  Link<br>} from &#39;react-router-dom&#39;</pre><pre>const users = [<br>  { id: 0, name: &#39;Michelle&#39;, friends: [ 1, 2, 3 ] },<br>  { id: 1, name: &#39;Sean&#39;, friends: [ 0, 3 ] },<br>  { id: 2, name: &#39;Kim&#39;, friends: [ 0, 1, 3 ], },<br>  { id: 3, name: &#39;David&#39;, friends: [ 1, 2 ] }<br>]</pre><pre>const Person = ({ match }) =&gt; {<br>  return (<br>    &lt;div&gt;<br>      PERSON<br>    &lt;/div&gt;<br>  )<br>}</pre><pre>class App extends React.Component {<br>  render() {<br>    return (<br>      &lt;Router&gt;<br>        &lt;Person /&gt;<br>      &lt;/Router&gt;<br>    )<br>  }<br>}</pre><pre>export default App</pre><p>Now what we need to do is figure out how to get the specific friend’s information from our users array so we can grab their name and render their friends. You may notice a problem here. Eventually Person is going to be rendered by React Router so it’ll be passed a match prop. It’s this match prop we’ll use to get the current pathname and (with help from users) the person’s name and friends list. The problem is we’re rendering Person manually inside the main App component to kick off the recursion. That means match is going to be undefined the first time Person is rendered. The solution to this problem is simpler than it may seem. When we first manually render &lt;Person /&gt; we’ll need to pass it a match prop just as React Router would.</p><pre>class App extends React.Component {<br>  render() {<br>    return (<br>      &lt;Router&gt;<br>        &lt;Person match={{ params: { id: 0 }, url: &#39;&#39; }}/&gt;<br>      &lt;/Router&gt;<br>    )<br>  }<br>}</pre><p>Now, every time Person is rendered, including the first time, it’ll be passed a match prop which will contain two things we need, url for rendering our Route and Links and params.id so we can figure out which person is being rendered.</p><p>Alright back to the main goal at hand. Person needs to</p><ol><li>It should render a Link component for every one of that specific person’s friends.</li><li>It should render a Route component which will match for the current pathname + /:id.</li></ol><p>Let’s tackle #1. Before we can render any Links, we need to get the person’s friends. We already know the person’s id from match.params.id. Using that knowledge with the Array.find method means getting the friends info should be pretty straight forward. We’ll create a helper function for it.</p><pre>const users = [<br>  { id: 0, name: &#39;Michelle&#39;, friends: [ 1, 2, 3 ] },<br>  { id: 1, name: &#39;Sean&#39;, friends: [ 0, 3 ] },<br>  { id: 2, name: &#39;Kim&#39;, friends: [ 0, 1, 3 ], },<br>  { id: 3, name: &#39;David&#39;, friends: [ 1, 2 ] }<br>]</pre><pre>const find = (id) =&gt; users.find(p =&gt; p.id == id)</pre><pre>const Person = ({ match }) =&gt; {<br>  const person = find(match.params.id)</pre><pre>return (<br>    &lt;div&gt;<br>      PERSON<br>    &lt;/div&gt;<br>  )<br>}</pre><p>Slowly getting there. Now we have the person, let’s render some UI including the Link for each of their friends.</p><pre>const users = [<br>  { id: 0, name: &#39;Michelle&#39;, friends: [ 1, 2, 3 ] },<br>  { id: 1, name: &#39;Sean&#39;, friends: [ 0, 3 ] },<br>  { id: 2, name: &#39;Kim&#39;, friends: [ 0, 1, 3 ], },<br>  { id: 3, name: &#39;David&#39;, friends: [ 1, 2 ] }<br>]</pre><pre>const find = (id) =&gt; users.find(p =&gt; p.id == id)</pre><pre>const Person = ({ match }) =&gt; {<br>  const person = find(match.params.id)</pre><pre>return (<br>    &lt;div&gt;<br>      &lt;h3&gt;{person.name}’s Friends&lt;/h3&gt;<br>      &lt;ul&gt;<br>        {person.friends.map((id) =&gt; (<br>          &lt;li key={id}&gt;<br>            &lt;Link to={`${match.url}/${id}`}&gt;<br>              {find(id).name}<br>            &lt;/Link&gt;<br>          &lt;/li&gt;<br>        ))}<br>      &lt;/ul&gt;<br>    &lt;/div&gt;<br>  )<br>}</pre><p>We’re so close to being done. Now that we have a Link for each of the person’s friends, as mentioned in #2, we need to make sure we also render a Route.</p><pre>const Person = ({ match }) =&gt; {<br>  const person = find(match.params.id)</pre><pre>  return (<br>    &lt;div&gt;<br>      &lt;h3&gt;{person.name}’s Friends&lt;/h3&gt;<br>      &lt;ul&gt;<br>        {person.friends.map((id) =&gt; (<br>          &lt;li key={id}&gt;<br>            &lt;Link to={`${match.url}/${id}`}&gt;<br>              {find(id).name}<br>            &lt;/Link&gt;<br>          &lt;/li&gt;<br>        ))}<br>      &lt;/ul&gt;<br>      &lt;Route path={`${match.url}/:id`} component={Person}/&gt;<br>    &lt;/div&gt;<br>  )<br>}</pre><p>The full code now looks like this</p><pre>import React from &#39;react&#39;<br>import {<br>  BrowserRouter as Router,<br>  Route,<br>  Link<br>} from &#39;react-router-dom&#39;</pre><pre>const find = (id) =&gt; users.find(p =&gt; p.id == id)</pre><pre>const users = [<br>  { id: 0, name: &#39;Michelle&#39;, friends: [ 1, 2, 3 ] },<br>  { id: 1, name: &#39;Sean&#39;, friends: [ 0, 3 ] },<br>  { id: 2, name: &#39;Kim&#39;, friends: [ 0, 1, 3 ], },<br>  { id: 3, name: &#39;David&#39;, friends: [ 1, 2 ] }<br>]</pre><pre>const Person = ({ match }) =&gt; {<br>  const person = find(match.params.id)</pre><pre>  return (<br>    &lt;div&gt;<br>      &lt;h3&gt;{person.name}’s Friends&lt;/h3&gt;<br>      &lt;ul&gt;<br>        {person.friends.map((id) =&gt; (<br>          &lt;li key={id}&gt;<br>            &lt;Link to={`${match.url}/${id}`}&gt;<br>              {find(id).name}<br>            &lt;/Link&gt;<br>          &lt;/li&gt;<br>        ))}<br>      &lt;/ul&gt;<br>      &lt;Route path={`${match.url}/:id`} component={Person}/&gt;<br>    &lt;/div&gt;<br>  )<br>}</pre><pre>class App extends React.Component {<br>  render() {<br>    return (<br>      &lt;Router&gt;<br>        &lt;Person match={{ params: { id: 0 }, url: &#39;&#39; }}/&gt;<br>      &lt;/Router&gt;<br>    )<br>  }<br>}</pre><pre>export default App</pre><p>The first time Person is rendered, we pass it a mock match object. Then, Person renders a list of Links as well as a Route matching any of those Links. When a Link is clicked, the Route matches which renders another Person component which renders a list of Links and a new Route. This process continues theoretically forever as long as the user continues to click on any Links.</p><p><em>This was originally published at </em><a href="https://tylermcginnis.com/react-router-recursive-paths/"><em>tylermcginnis.com</em></a><em> as part of their </em><a href="https://tylermcginnis.com/courses/react-router/"><em>React Router </em></a><em>course.</em></p><figure><a href="https://medium.com/swlh"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YqDjlKFwScoQYQ62DWEdig.png" /></a></figure><h4>This story is published in <a href="https://medium.com/swlh">The Startup</a>, Medium’s largest entrepreneurship publication followed by +408,714 people.</h4><h4>Subscribe to receive <a href="http://growthsupply.com/the-startup-newsletter/">our top stories here</a>.</h4><figure><a href="https://medium.com/swlh"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ouK9XR4xuNWtCes-TIUNAw.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ebddae98f68" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/recursive-paths-with-react-router-3ebddae98f68">Recursive paths with React Router</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pass Props to React Router’s Link Component]]></title>
            <link>https://medium.com/hackernoon/pass-props-to-react-routers-link-component-2eebda7a63e1?source=rss-c52389e3ee63------2</link>
            <guid isPermaLink="false">https://medium.com/p/2eebda7a63e1</guid>
            <category><![CDATA[react-router]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Tyler McGinnis]]></dc:creator>
            <pubDate>Wed, 02 Jan 2019 20:25:40 GMT</pubDate>
            <atom:updated>2019-01-04T09:15:54.028Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WanzIfpXpwsDKSSHz6xQOw.jpeg" /></figure><p>Often times when building an app with React Router you’ll need to pass props through a Link component to the new route. In this post, we’ll break down how that process works.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FnmbX2QL7ZJc%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DnmbX2QL7ZJc&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FnmbX2QL7ZJc%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/eb462541b0d3521ddc9fc898011a053d/href">https://medium.com/media/eb462541b0d3521ddc9fc898011a053d/href</a></iframe><p>There are two different ways to pass data from a Link component through to the new route that’s being rendered. The first is through URL Parameters and the second is through state.</p><p>First, let’s take a look at URL parameters. If you’ve read our <a href="https://tylermcginnis.com/react-router-url-parameters/">URL Parameters</a> post, you’ll be familiar with this example. Say we were in charge of building out the Route that renders Twitter’s <a href="https://twitter.com/tylermcginnis">profile</a> page. If created with React Router, that route may look like this</p><pre>&lt;Route path=&#39;/:handle&#39; component={Profile} /&gt;</pre><p>Notice that handle is going to be dynamic. It could be anything from tylermcginnis or dan_abramov to realDonaldTrump.</p><p>So in our app we may have a Link component that looks like this</p><pre>&lt;Link to=&#39;/tylermcginnis&#39;&gt;Tyler McGinnis&lt;/Link&gt;</pre><p>If clicked, the user would be taken to /tylermcginnis and the Profile component would be able to access the dynamic handle (tylermcginnis) from props.match.params.handle.</p><pre>class Profile extends React.Component {<br>  state = {<br>    user: null<br>  }<br>  componentDidMount () {<br>    const { handle } = this.props.match.params</pre><pre>    fetch(`<a href="https://api.twitter.com/user/${handle}`">https://api.twitter.com/user/${handle}`</a>)<br>      .then((user) =&gt; {<br>        this.setState(() =&gt; ({ user }))<br>      })<br>  }<br>  render() {<br>    ...<br>  }<br>}</pre><p>URL parameters are great, but they’re not really meant to serve as a way to get data from one route to another as they’re limited to just strings. What if instead of just a string, we wanted to pass something a little more complex, like an object or an array? There would be no way to do that with URL parameters. This brings us to the second way to pass data from one route to another and that’s with state.</p><p>Going back to our example from earlier, what if we wanted to pass along if the user is coming from a certain route through to the Profile component when the user clicks on the Link? React Router gives us a way to do that and the API looks like this</p><pre>&lt;Link to={{<br>  pathname: &#39;/tylermcginnis&#39;,<br>  state: {<br>    fromNotifications: true<br>  }<br>}}&gt;Tyler McGinnis&lt;/Link&gt;</pre><p>Now, the component that’s being rendered for that route (in this case, Profile) would be able to access fromNotifications by accessing props.location.state.</p><pre>class Profile extends React.Component {<br>  state = {<br>    user: null<br>  }<br>  componentDidMount () {<br>    const { handle } = this.props.match.params<br>    const { fromNotifications } = this.props.location.state</pre><pre>    fetch(`<a href="https://api.twitter.com/user/${handle}`">https://api.twitter.com/user/${handle}`</a>)<br>      .then((user) =&gt; {<br>        this.setState(() =&gt; ({ user }))<br>      })<br>  }<br>  render() {<br>    ...<br>  }<br>}</pre><p>To recap, there are two ways to pass data from a Link through to the new route: URL parameters and state. URL parameters work great for strings, but break down after that. By making the Links to prop an object, you can pass along any sort of data you need under the state property and that data can be accessed in the new route under props.location.state.</p><p><em>This was originally published at </em><a href="https://tylermcginnis.com/react-router-pass-props-to-link/"><em>tylermcginnis.com</em></a><em> as part of their </em><a href="https://tylermcginnis.com/courses/react-router/"><em>React Router</em></a><em> course.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2eebda7a63e1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/pass-props-to-react-routers-link-component-2eebda7a63e1">Pass Props to React Router’s Link Component</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[When to use var vs let vs const in JavaScript]]></title>
            <link>https://medium.com/free-code-camp/var-vs-let-vs-const-in-javascript-2954ae48c037?source=rss-c52389e3ee63------2</link>
            <guid isPermaLink="false">https://medium.com/p/2954ae48c037</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Tyler McGinnis]]></dc:creator>
            <pubDate>Tue, 01 Jan 2019 18:06:02 GMT</pubDate>
            <atom:updated>2019-01-04T18:49:38.572Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1NnEsagl3a_L9lWWsKHROA.png" /></figure><p>In this post you’ll learn two new ways to create variables in JavaScript (ES6), let and const. Along the way we’ll look at the differences between var, let, and const as well as cover topics like function vs block scope, variable hoisting, and immutability.</p><p>If you prefer to watch a video, check this out:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F6vBYfLCE9-Q%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D6vBYfLCE9-Q&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F6vBYfLCE9-Q%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/8dfebde399ea3406060047bdb9c1094a/href">https://medium.com/media/8dfebde399ea3406060047bdb9c1094a/href</a></iframe><p>ES2015 (or ES6) introduced two new ways to create variables, let and const. But before we actually dive into the differences between var, let, and const, there are some prerequisites you need to know first. They are variable declarations vs initialization, scope (specifically function scope), and hoisting.</p><h4>Variable Declaration vs Initialization</h4><p>A variable declaration introduces a new identifier.</p><pre>var declaration</pre><p>Above we create a new identifier called declaration. In JavaScript, variables are initialized with the value of undefined when they are created. What that means is if we try to log the declaration variable, we’ll get undefined.</p><pre>var declaration </pre><pre>console.log(declaration)</pre><p>So if we log the declaration variable, we get undefined.</p><p>In contrast to variable declaration, variable initialization is when you first assign a value to a variable.</p><pre>var declaration</pre><pre>console.log(declaration) // undefined</pre><pre>declaration = &#39;This is an initialization&#39;</pre><p>So here we’re initializing the declaration variable by assigning it to a string.</p><p>This leads us to our second concept, Scope.</p><h4>Scope</h4><p>Scope defines where variables and functions are accessible inside of your program. In JavaScript, there are two kinds of scope — <strong>global scope</strong>, and <strong>function scope</strong>. According to the official spec,</p><blockquote><em>“If the variable statement occurs inside a FunctionDeclaration, the variables are defined with function-local scope in that function.”.</em></blockquote><p>What that means is if you create a variable with var, that variable is “scoped” to the function it was created in and is only accessible inside of that function or, any nested functions.</p><pre>function getDate () {<br>  var date = new Date()</pre><pre>  return date<br>}</pre><pre>getDate()<br>console.log(date) // ❌ Reference Error</pre><p>Above we try to access a variable outside of the function it was declared. Because date is “scoped” to the getDate function, it’s only accessible inside of getDate itself or any nested functions inside of getDate (as seen below).</p><pre>function getDate () {<br>  var date = new Date()</pre><pre>  function formatDate () {<br>    return date.toDateString().slice(4) // ✅ <br>  }</pre><pre>  return formatDate()<br>}</pre><pre>getDate()<br>console.log(date) // ❌ Reference Error</pre><p>Now let’s look at a more advanced example. Say we had an array of prices and we needed a function that took in that array as well as a discount and returned us a new array of discounted prices. The end goal might look something like this:</p><pre>discountPrices([100, 200, 300], .5)</pre><p>And the implementation might look something like this:</p><pre>function discountPrices (prices, discount) {<br>  var discounted = []</pre><pre>  for (var i = 0; i &lt; prices.length; i++) {<br>    var discountedPrice = prices[i] * (1 - discount)<br>    var finalPrice = Math.round(discountedPrice * 100) / 100<br>    discounted.push(finalPrice)<br>  }</pre><pre>  return discounted<br>}</pre><p>Seems simple enough, but what does this have to do with block scope? Take a look at that for loop. Are the variables declared inside of it accessible outside of it? Turns out, they are.</p><pre>function discountPrices (prices, discount) {<br>  var discounted = []</pre><pre>  for (var i = 0; i &lt; prices.length; i++) {<br>    var discountedPrice = prices[i] * (1 - discount)<br>    var finalPrice = Math.round(discountedPrice * 100) / 100<br>    discounted.push(finalPrice)<br>  }</pre><pre>  console.log(i) // 3<br>  console.log(discountedPrice) // 150<br>  console.log(finalPrice) // 150</pre><pre>  return discounted<br>}</pre><p>If JavaScript is the only programming language you know, you may not think anything of this. However, if you’re coming to JavaScript from another programming language, specifically a programming language that is blocked scope, you’re probably a little bit concerned about what’s going on here.</p><p>It’s not really broken, it’s just kind of weird. There’s not really a reason to still have access to i, discountedPrice, and finalPrice outside of the for loop. It doesn’t really do us any good and it may even cause us harm in some cases. However, since variables declared with var are function scoped, you do.</p><p>Now that we’ve discussed variable declarations, initializations, and scope, the last thing we need to flush out before we dive into let and const is hoisting.</p><h4>Hoisting</h4><p>Remember earlier we said that “In JavaScript, variables are initialized with the value of undefined when they are created.” Turns out, that’s all that “Hoisting” is. The JavaScript interpreter will assign variable declarations a default value of undefined during what’s called the “Creation” phase.</p><blockquote><em>For a much more in depth guide on the Creation Phase, Hoisting, and Scopes see </em><a href="https://tylermcginnis.com/ultimate-guide-to-execution-contexts-hoisting-scopes-and-closures-in-javascript/"><em>“</em><strong><em>The Ultimate Guide to Hoisting, Scopes, and Closures in JavaScript</em></strong><em>”</em></a><em>.</em></blockquote><p>Let’s take a look at the previous example and see how hoisting affects it.</p><pre>function discountPrices (prices, discount) {<br>  var discounted = undefined<br>  var i = undefined<br>  var discountedPrice = undefined<br>  var finalPrice = undefined</pre><pre>  discounted = []<br>  for (var i = 0; i &lt; prices.length; i++) {<br>    discountedPrice = prices[i] * (1 - discount)<br>    finalPrice = Math.round(discountedPrice * 100) / 100<br>    discounted.push(finalPrice)<br>  }</pre><pre>  console.log(i) // 3<br>  console.log(discountedPrice) // 150<br>  console.log(finalPrice) // 150</pre><pre>  return discounted<br>}</pre><p>Notice all the variable declarations were assigned a default value of undefined. That’s why if you try access one of those variables <strong>before</strong> it was actually declared, you’ll just get undefined.</p><pre>function discountPrices (prices, discount) {<br>  console.log(discounted) // undefined</pre><pre>  var discounted = []</pre><pre>  for (var i = 0; i &lt; prices.length; i++) {<br>    var discountedPrice = prices[i] * (1 - discount)<br>    var finalPrice = Math.round(discountedPrice * 100) / 100<br>    discounted.push(finalPrice)<br>  }</pre><pre>  console.log(i) // 3<br>  console.log(discountedPrice) // 150<br>  console.log(finalPrice) // 150</pre><pre>  return discounted<br>}</pre><p>Now that you know everything there is to know about var, let’s finally talk about the whole point of why you’re here: what’s the difference between var, let, and const?</p><h4>var VS let VS const</h4><p>First, let’s compare var and let. The main difference between var and let is that instead of being function scoped, let is block scoped. What that means is that a variable created with the let keyword is available inside the “block” that it was created in as well as any nested blocks. When I say “block”, I mean anything surrounded by a curly brace {} like in a for loop or an if statement.</p><p>So let’s look back to our discountPrices function one last time.</p><pre>function discountPrices (prices, discount) {<br>  var discounted = []</pre><pre>  for (var i = 0; i &lt; prices.length; i++) {<br>    var discountedPrice = prices[i] * (1 - discount)<br>    var finalPrice = Math.round(discountedPrice * 100) / 100<br>    discounted.push(finalPrice)<br>  }</pre><pre>  console.log(i) // 3<br>  console.log(discountedPrice) // 150<br>  console.log(finalPrice) // 150</pre><pre>  return discounted<br>}</pre><p>Remember that we were able to log i, discountedPrice, and finalPrice outside of the for loop since they were declared with var and var is function scoped. But now, what happens if we change those var declarations to use let and try to run it?</p><pre>function discountPrices (prices, discount) {<br>  let discounted = []</pre><pre>  for (let i = 0; i &lt; prices.length; i++) {<br>    let discountedPrice = prices[i] * (1 - discount)<br>    let finalPrice = Math.round(discountedPrice * 100) / 100<br>    discounted.push(finalPrice)<br>  }</pre><pre>  console.log(i) // 3<br>  console.log(discountedPrice) // 150<br>  console.log(finalPrice) // 150</pre><pre>  return discounted<br>}</pre><pre>discountPrices([100, 200, 300], .5) // ❌ ReferenceError: i is not defined</pre><p>🙅‍♀️ We get ReferenceError: i is not defined. What this tells us is that variables declared with let are block scoped, not function scoped. So trying to access i (or discountedPrice or finalPrice) outside of the “block” they were declared in is going to give us a reference error as we just barely saw.</p><pre>var VS let</pre><pre>var: function scoped</pre><pre>let: block scoped</pre><p>The next difference has to do with Hoisting. Earlier we said that the definition of hoisting was “The JavaScript interpreter will assign variable declarations a default value of undefined during what’s called the ‘Creation’ phase.” We even saw this in action by logging a variable before it was declared (you get undefined).</p><pre>function discountPrices (prices, discount) {<br>  console.log(discounted) // undefined</pre><pre>  var discounted = []</pre><pre>  for (var i = 0; i &lt; prices.length; i++) {<br>    var discountedPrice = prices[i] * (1 - discount)<br>    var finalPrice = Math.round(discountedPrice * 100) / 100<br>    discounted.push(finalPrice)<br>  }</pre><pre>  console.log(i) // 3<br>  console.log(discountedPrice) // 150<br>  console.log(finalPrice) // 150</pre><pre>  return discounted<br>}</pre><p>I can’t think of any use case where you’d actually want to access a variable before it was declared. It seems like throwing a ReferenceError would be a better default than returning undefined.</p><p>In fact, this is exactly what let does. If you try to access a variable declared with let before it’s declared, instead of getting undefined (like with those variables declared with var), you’ll get a ReferenceError.</p><pre>function discountPrices (prices, discount) {<br>  console.log(discounted) // ❌ ReferenceError</pre><pre>  let discounted = []</pre><pre>  for (let i = 0; i &lt; prices.length; i++) {<br>    let discountedPrice = prices[i] * (1 - discount)<br>    let finalPrice = Math.round(discountedPrice * 100) / 100<br>    discounted.push(finalPrice)<br>  }</pre><pre>  console.log(i) // 3<br>  console.log(discountedPrice) // 150<br>  console.log(finalPrice) // 150</pre><pre>  return discounted<br>}</pre><pre>var VS let</pre><pre>var: <br>  function scoped<br>  undefined when accessing a variable before it&#39;s declared</pre><pre>let: <br>  block scoped<br>  ReferenceError when accessing a variable before it&#39;s declared</pre><h4>let VS const</h4><p>Now that you understand the difference between var and let, what about const? Turns out, const is almost exactly the same as let. However, the only difference is that once you’ve assigned a value to a variable using const, you can’t reassign it to a new value.</p><pre>let name = &#39;Tyler&#39;<br>const handle = &#39;tylermcginnis&#39;</pre><pre>name = &#39;Tyler McGinnis&#39; // ✅<br>handle = &#39;<a href="http://twitter.com/tylermcginnis">@tylermcginnis</a>&#39; // ❌ TypeError: Assignment to constant variable.</pre><p>The take away above is that variables declared with let can be re-assigned, but variables declared with const can’t be.</p><p>Cool, so anytime you want a variable to be immutable, you can declare it with const. Well, not quite. Just because a variable is declared with const doesn’t mean it’s immutable, all it means is the value can’t be re-assigned. Here’s a good example.</p><pre>const person = {<br>  name: &#39;Kim Kardashian&#39;<br>}</pre><pre>person.name = &#39;Kim Kardashian West&#39; // ✅</pre><pre>person = {} // ❌ Assignment to constant variable.</pre><p>Notice that changing a property on an object isn’t reassigning it, so even though an object is declared with const, that doesn’t mean you can’t mutate any of its properties. It only means you can’t reassign it to a new value.</p><p>Now the most important question we haven’t answered yet: should you use var, let, or const? The most popular opinion, and the opinion that I subscribe to, is that you should always use const unless you know the variable is going to change. The reason for this is by using const, you’re signaling to your future self as well as any other future developers that have to read your code that this variable shouldn’t change. If it will need to change (like in a for loop), you should use let.</p><p>So between variables that change and variables that don’t change, there’s not much left. That means you shouldn’t ever have to use var again.</p><p>Now the unpopular opinion, though it still has some validity to it, is that you should never use const because even though you’re trying to signal that the variable is immutable, as we saw above, that’s not entirely the case. Developers who subscribe to this opinion always use let unless they have variables that are actually constants like _LOCATION_ = ....</p><p>So to recap, var is function scoped and if you try to use a variable declared with var before the actual declaration, you’ll just get undefined. const and let are blocked scoped and if you try to use variable declared with let or const before the declaration you’ll get a ReferenceError. Finally the difference between let and const is that once you’ve assigned a value to const, you can’t reassign it, but with let, you can.</p><pre>var VS let VS const</pre><pre>var: <br>  function scoped<br>  undefined when accessing a variable before it&#39;s declared</pre><pre>let: <br>  block scoped<br>  ReferenceError when accessing a variable before it&#39;s declared</pre><pre>const:<br>  block scoped<br>  ReferenceError when accessing a variable before it&#39;s declared<br>  can&#39;t be reassigned</pre><p><em>This was originally published at </em><a href="https://tylermcginnis.com/var-let-const/"><em>tylermcginnis.com</em></a><em> as part of their </em><a href="https://tylermcginnis.com/courses/modern-javascript/"><em>Modern JavaScript</em></a><em> course.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2954ae48c037" width="1" height="1" alt=""><hr><p><a href="https://medium.com/free-code-camp/var-vs-let-vs-const-in-javascript-2954ae48c037">When to use var vs let vs const in JavaScript</a> was originally published in <a href="https://medium.com/free-code-camp">We’ve moved to freeCodeCamp.org/news</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rendering a Sidebar or Breadcrumbs with React Router v4]]></title>
            <link>https://medium.com/hackernoon/rendering-a-sidebar-or-breadcrumbs-with-react-router-v4-94365f6a53ed?source=rss-c52389e3ee63------2</link>
            <guid isPermaLink="false">https://medium.com/p/94365f6a53ed</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-router]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Tyler McGinnis]]></dc:creator>
            <pubDate>Tue, 11 Dec 2018 20:03:17 GMT</pubDate>
            <atom:updated>2018-12-11T20:03:17.815Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EcvkY4Q06MfSdPqArF4aEA.jpeg" /></figure><p>When building an app with React Router, often you’ll want to implement a sidebar or breadcrumb navbar. In this post you’ll learn how that’s done with React Router by breaking down the Sidebar example from the React Router documentation.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FiXh3VvyC3hM%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DiXh3VvyC3hM&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FiXh3VvyC3hM%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/dff521762d954d6924897a2f83ac7e20/href">https://medium.com/media/dff521762d954d6924897a2f83ac7e20/href</a></iframe><p>A common UI pattern is to have a sidebar or breadcrumb navbar in your app. Because React Router allows you to render and match more than one Route per page, implementing this pattern is pretty straight forward. The goal of this post is to show how you can, by rendering multiple Routes, render separate components at separate parts of your page based on the path (like a sidebar).</p><p>The first thing we’ll do, and really the secret to this post, is to create a routes array. Each item in the array is going to contain all the information about the specific route, and also which component should be rendered.</p><pre>const routes = [<br>  { path: &#39;/&#39;,<br>    exact: true,<br>    sidebar: () =&gt; &lt;div&gt;home!&lt;/div&gt;,<br>    main: () =&gt; &lt;h2&gt;Home&lt;/h2&gt;<br>  },<br>  { path: &#39;/bubblegum&#39;,<br>    sidebar: () =&gt; &lt;div&gt;bubblegum!&lt;/div&gt;,<br>    main: () =&gt; &lt;h2&gt;Bubblegum&lt;/h2&gt;<br>  },<br>  { path: &#39;/shoelaces&#39;,<br>    sidebar: () =&gt; &lt;div&gt;shoelaces!&lt;/div&gt;,<br>    main: () =&gt; &lt;h2&gt;Shoelaces&lt;/h2&gt;<br>  }<br>]</pre><p>Now, because we’ve abstracted our routes to this array, whenever we want to render any Routes we can map over it and specify which component should be rendered (main or sidebar). To show how that’s done, let’s first build out the basic skeleton for our app.</p><pre>import React from &#39;react&#39;<br>import {<br>  BrowserRouter as Router,<br>  Route,<br>  Link,<br>} from &#39;react-router-dom&#39;</pre><pre>const routes = [<br>  { path: &#39;/&#39;,<br>    exact: true,<br>    sidebar: () =&gt; &lt;div&gt;home!&lt;/div&gt;,<br>    main: () =&gt; &lt;h2&gt;Home&lt;/h2&gt;<br>  },<br>  { path: &#39;/bubblegum&#39;,<br>    sidebar: () =&gt; &lt;div&gt;bubblegum!&lt;/div&gt;,<br>    main: () =&gt; &lt;h2&gt;Bubblegum&lt;/h2&gt;<br>  },<br>  { path: &#39;/shoelaces&#39;,<br>    sidebar: () =&gt; &lt;div&gt;shoelaces!&lt;/div&gt;,<br>    main: () =&gt; &lt;h2&gt;Shoelaces&lt;/h2&gt;<br>  }<br>]</pre><pre>class App extends React.Component {<br>  render() {<br>    return (<br>      &lt;Router&gt;<br>        &lt;div style={{ display: &#39;flex&#39; }}&gt;<br>          &lt;div style={{<br>            padding: &#39;10px&#39;,<br>            width: &#39;40%&#39;,<br>            background: &#39;#f0f0f0&#39;<br>          }}&gt;<br>            &lt;ul style={{ listStyleType: &#39;none&#39;, padding: 0 }}&gt;<br>              &lt;li&gt;&lt;Link to=&quot;/&quot;&gt;Home&lt;/Link&gt;&lt;/li&gt;<br>              &lt;li&gt;&lt;Link to=&quot;/bubblegum&quot;&gt;Bubblegum&lt;/Link&gt;&lt;/li&gt;<br>              &lt;li&gt;&lt;Link to=&quot;/shoelaces&quot;&gt;Shoelaces&lt;/Link&gt;&lt;/li&gt;<br>            &lt;/ul&gt;</pre><pre>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      &lt;/Router&gt;<br>    )<br>  }<br>}</pre><pre>export default App</pre><p>Now remember the goal here is to render multiple components in different places of the app, based on the path. We already have our routes array, so wherever we want to render some Routes we can just map over it. First, let’s add some Routes to the sidebar (inside of our nav).</p><pre>render() {<br>  return (<br>    &lt;Router&gt;<br>      &lt;div style={{ display: &#39;flex&#39; }}&gt;<br>        &lt;div style={{<br>          padding: &#39;10px&#39;,<br>          width: &#39;40%&#39;,<br>          background: &#39;#f0f0f0&#39;<br>        }}&gt;<br>          &lt;ul style={{ listStyleType: &#39;none&#39;, padding: 0 }}&gt;<br>            &lt;li&gt;&lt;Link to=&quot;/&quot;&gt;Home&lt;/Link&gt;&lt;/li&gt;<br>            &lt;li&gt;&lt;Link to=&quot;/bubblegum&quot;&gt;Bubblegum&lt;/Link&gt;&lt;/li&gt;<br>            &lt;li&gt;&lt;Link to=&quot;/shoelaces&quot;&gt;Shoelaces&lt;/Link&gt;&lt;/li&gt;<br>          &lt;/ul&gt;<br>          {routes.map((route) =&gt; (<br>            &lt;Route<br>              key={route.path}<br>              path={route.path}<br>              exact={route.exact}<br>              component={route.sidebar}<br>            /&gt;<br>          ))}<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>    &lt;/Router&gt;<br>  )<br>}</pre><p>The biggest thing to notice is that we’ve passed in route.sidebar to Routes component prop. This is the crux of the example and shows the importance of the routes array we created earlier. Now whenever the location matches the path, the sidebar component will be rendered. However, we don’t just want to stop there. We also want to render a component in the main body of our app when the location matches the path. To do that, we’ll map over routes again but instead of passing component route.sidebar, we’ll pass it route.main.</p><pre>render() {<br>  return (<br>    &lt;Router&gt;<br>      &lt;div style={{ display: &#39;flex&#39; }}&gt;<br>        &lt;div style={{<br>          padding: &#39;10px&#39;,<br>          width: &#39;40%&#39;,<br>          background: &#39;#f0f0f0&#39;<br>        }}&gt;<br>          &lt;ul style={{ listStyleType: &#39;none&#39;, padding: 0 }}&gt;<br>            &lt;li&gt;&lt;Link to=&quot;/&quot;&gt;Home&lt;/Link&gt;&lt;/li&gt;<br>            &lt;li&gt;&lt;Link to=&quot;/bubblegum&quot;&gt;Bubblegum&lt;/Link&gt;&lt;/li&gt;<br>            &lt;li&gt;&lt;Link to=&quot;/shoelaces&quot;&gt;Shoelaces&lt;/Link&gt;&lt;/li&gt;<br>          &lt;/ul&gt;<br>          {routes.map((route) =&gt; (<br>            &lt;Route<br>              key={route.path}<br>              path={route.path}<br>              exact={route.exact}<br>              component={route.sidebar}<br>            /&gt;<br>          ))}<br>        &lt;/div&gt;</pre><pre>        &lt;div style={{ flex: 1, padding: &#39;10px&#39; }}&gt;<br>          {routes.map((route) =&gt; (<br>            &lt;Route<br>              key={route.path}<br>              path={route.path}<br>              exact={route.exact}<br>              component={route.main}<br>            /&gt;<br>          ))}<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>    &lt;/Router&gt;<br>  )<br>}</pre><p>🕺. Now, because React Router allows us to render and match more than one Route on a page, and because we abstracted our routes to an array, we can render different components at different sections of our page whenever the location matches the Routes path.</p><p><em>Originally published at </em><a href="https://tylermcginnis.com/react-router-sidebar-breadcrumbs/"><em>tylermcginnis.com</em></a><em> as part of their </em><a href="https://tylermcginnis.com/courses/react-router/"><em>React Router</em></a><em> course.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=94365f6a53ed" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/rendering-a-sidebar-or-breadcrumbs-with-react-router-v4-94365f6a53ed">Rendering a Sidebar or Breadcrumbs with React Router v4</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript Inheritance and the Prototype Chain]]></title>
            <link>https://medium.com/free-code-camp/javascript-inheritance-and-the-prototype-chain-d4298619bdae?source=rss-c52389e3ee63------2</link>
            <guid isPermaLink="false">https://medium.com/p/d4298619bdae</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Tyler McGinnis]]></dc:creator>
            <pubDate>Mon, 10 Dec 2018 19:02:39 GMT</pubDate>
            <atom:updated>2018-12-18T17:46:02.428Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0n0aKBnY5k7fj78GV0IDZg.jpeg" /></figure><blockquote><em>This post is designed to be read after you read </em><a href="https://tylermcginnis.com/javascript-private-and-public-class-fields/"><strong><em>JavaScript Private and Public Class Fields</em></strong></a><em>.</em></blockquote><p>If you prefer to watch a video instead,</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FMiKdRJc4ooE%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DMiKdRJc4ooE&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FMiKdRJc4ooE%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c8ff0a29c1f60dfe13cfe64baa87676/href">https://medium.com/media/3c8ff0a29c1f60dfe13cfe64baa87676/href</a></iframe><p>Previously we learned how to create an Animal class both in ES5 as well as in ES6. We also learned how to share methods across those classes using JavaScript’s prototype. To review, here’s the code we saw in an earlier post.</p><pre>// ES5<br>function Animal (name, energy) {<br>  this.name = name<br>  this.energy = energy<br>}</pre><pre>Animal.prototype.eat = function (amount) {<br>  console.log(`${this.name} is eating.`)<br>  this.energy += amount<br>}</pre><pre>Animal.prototype.sleep = function (length) {<br>  console.log(`${this.name} is sleeping.`)<br>  this.energy += length<br>}</pre><pre>Animal.prototype.play = function (length) {<br>  console.log(`${this.name} is playing.`)<br>  this.energy -= length<br>}</pre><pre>const leo = new Animal(&#39;Leo&#39;, 7)<br></pre><pre>// ES6<br>class Animal {<br>  constructor(name, energy) {<br>    this.name = name<br>    this.energy = energy<br>  }<br>  eat(amount) {<br>    console.log(`${this.name} is eating.`)<br>    this.energy += amount<br>  }<br>  sleep() {<br>    console.log(`${this.name} is sleeping.`)<br>    this.energy += length<br>  }<br>  play() {<br>    console.log(`${this.name} is playing.`)<br>    this.energy -= length<br>  }<br>}</pre><pre>const leo = new Animal(&#39;Leo&#39;, 7)</pre><p>Now let’s say we wanted to start making individual classes for specific animals. For example, what if we wanted to start making a bunch of dog instances. What properties and methods will these dogs have?</p><p>Well, similar to our Animal class, we could give each dog a name, an energy level, and the ability to eat, sleep, and play. Unique to our Dog class, we could also give them a breed property as well as the ability to bark. In ES5, our Dog class could look something like this</p><pre>function Dog (name, energy, breed) {<br>  this.name = name<br>  this.energy = energy<br>  this.breed = breed<br>}</pre><pre>Dog.prototype.eat = function (amount) {<br>  console.log(`${this.name} is eating.`)<br>  this.energy += amount<br>}</pre><pre>Dog.prototype.sleep = function (length) {<br>  console.log(`${this.name} is sleeping.`)<br>  this.energy += length<br>}</pre><pre>Dog.prototype.play = function (length) {<br>  console.log(`${this.name} is playing.`)<br>  this.energy -= length<br>}</pre><pre>Dog.prototype.bark = function () {<br>  console.log(&#39;Woof-Woof!&#39;)<br>  this.energy -= .1<br>}</pre><pre>const charlie = new Dog(&#39;Charlie&#39;, 10, &#39;Goldendoodle&#39;)</pre><p>Alright, well… we just recreated the Animal class and added a few new properties to it. If we wanted to create another animal, say a Cat, at this point we’d again have to create a Cat class, duplicate all the common logic located in the Animal class to it, then add on Cat specific properties just like we did with the Dog class. In fact, we’d have to do this for each different type of animal we created.</p><pre>function Dog (name, energy, breed) {}</pre><pre>function Cat (name, energy, declawed) {}</pre><pre>function Giraffe (name, energy, height) {}</pre><pre>function Monkey (name, energy, domesticated) {}</pre><p>This work, but it seems wasteful. The Animal class is the perfect base class. What that means is that it has all the properties that each one of our animals has in common. Whether we’re creating a dog, cat, giraffe, or monkey, all of them will have a name, energy level, and the ability to eat, sleep, and play.</p><p>With that said, is there a way we can utilize the Animal class whenever we create the individual classes for each different animal? Let’s try it out. I’ll paste the Animal class again below for easy reference.</p><pre>function Animal (name, energy) {<br>  this.name = name<br>  this.energy = energy<br>}</pre><pre>Animal.prototype.eat = function (amount) {<br>  console.log(`${this.name} is eating.`)<br>  this.energy += amount<br>}</pre><pre>Animal.prototype.sleep = function (length) {<br>  console.log(`${this.name} is sleeping.`)<br>  this.energy += length<br>}</pre><pre>Animal.prototype.play = function (length) {<br>  console.log(`${this.name} is playing.`)<br>  this.energy -= length<br>}</pre><pre>function Dog (name, energy, breed) {</pre><pre>}</pre><p>What are some things we know about the Dog constructor function above?</p><p>First, we know it takes 3 arguments, name, energy, and breed.</p><p>Second, we know it’s going to be called with the new keyword so we’ll have a this object.</p><p>And third, we know we need to utilize the Animal function so that any instance of dog will have a name, energy level, and be able to eat, sleep, and play.</p><p>It’s the third one that’s the tricky one. The way you “utilize” a function is by calling it. So we know that inside of Dog, we want to call Animal. What we need to figure out though is how we can invoke Animal in the context of Dog. What that means it that we want to call Animal with the this keyword from Dog. If we do that correctly, then this inside of the Dog function will have all the properties of Animal (name, energy). If you remember from a <a href="https://tylermcginnis.com/this-keyword-call-apply-bind-javascript/">previous section</a>, every function in JavaScript has a .call method on it.</p><blockquote><em>.call() is a method on every function that allows you to invoke the function specifying in what context the function will be invoked.</em></blockquote><p>This sounds like exactly what we need. We want to invoke Animal in the context of Dog.</p><pre>function Dog (name, energy, breed) {<br>  Animal.call(this, name, energy)</pre><pre>  this.breed = breed<br>}</pre><pre>const charlie = new Dog(&#39;Charlie&#39;, 10, &#39;Goldendoodle&#39;)</pre><pre>charlie.name // Charlie<br>charlie.energy // 10<br>charlie.breed // Goldendoodle</pre><p>Solid, we’re half-way there. You’ll notice in the code above that because of this line Animal.call(this, name, energy), every instance of Dog will now have a name and energy property. Again, the reason for that is because it’s as if we ran the Animal function with the this keyword generated from Dog. Then after we added a name and energy property to this, we also added a breed property just as we normally would.</p><p>Remember the goal here is to have each instance of Dog have not only all the properties of Animal, but also all the methods as well. If you run the code above, you’ll notice that if you try to run charlie.eat(10) you’ll get an error. Currently every instance of Dog will have the properties of Animal (name and energy), but we haven’t done anything to make sure that they also have the methods (play, eat, sleep).</p><p>Let’s think about how we can solve this. We know that all the Animal’s methods are located on Animal.prototype. What that means is we somehow want to make sure that all instances of Dog will have access to the methods on Animal.prototype.</p><p>What if we used our good friend Object.create here? If you’ll remember, Object.create allows you to create an object which will delegate to another object on failed lookups. So in our case, the object we want to create is going to be Dog’s prototype and the object we want to delegate to on failed lookups is Animal.prototype.</p><pre>function Dog (name, energy, breed) {<br>  Animal.call(this, name, energy)</pre><pre>  this.breed = breed<br>}</pre><pre>Dog.prototype = Object.create(Animal.prototype)</pre><p>Now, whenever there’s a failed lookup on an instance of Dog, JavaScript will delegate that lookup to Animal.prototype. If this is still a little fuzzy, re-read <a href="https://tylermcginnis.com/beginners-guide-to-javascript-prototype/">A Beginner’s Guide to JavaScript’s Prototype</a> where we talk all about Object.create and JavaScript’s prototype.</p><p>Let’s look at the full code together then we’ll walk through what happens.</p><pre>function Animal (name, energy) {<br>  this.name = name<br>  this.energy = energy<br>}</pre><pre>Animal.prototype.eat = function (amount) {<br>  console.log(`${this.name} is eating.`)<br>  this.energy += amount<br>}</pre><pre>Animal.prototype.sleep = function (length) {<br>  console.log(`${this.name} is sleeping.`)<br>  this.energy += length<br>}</pre><pre>Animal.prototype.play = function (length) {<br>  console.log(`${this.name} is playing.`)<br>  this.energy -= length<br>}</pre><pre>function Dog (name, energy, breed) {<br>  Animal.call(this, name, energy)</pre><pre>  this.breed = breed<br>}</pre><pre>Dog.prototype = Object.create(Animal.prototype)</pre><p>Now we’ve created our base class (Animal) as well as our subclass (Dog), let’s see what it looks like under the hood when we create an instance of Dog.</p><pre>const charlie = new Dog(&#39;Charlie&#39;, 10, &#39;Goldendoodle&#39;)</pre><pre>charlie.name // Charlie<br>charlie.energy // 10<br>charlie.breed // Goldendoodle</pre><p>Nothing fancy so far, but let’s look at what happens when we invoke a method located on Animal.</p><pre>charlie.eat(10)</pre><pre>/*<br>1) JavaScript checks if charlie has an eat property - it doesn&#39;t.<br>2) JavaScript then checks if Dog.prototype has an eat property<br>    - it doesn&#39;t.<br>3) JavaScript then checks if Animal.prototype has an eat property<br>    - it does so it calls it.<br>*/</pre><p>The reason Dog.prototype gets checked is because when we created a new instance of Dog, we used the new keyword. Under the hood, the this object that was created for us delegates to Dog.prototype (seen in comments below).</p><pre>function Dog (name, energy, breed) {<br>  // this = Object.create(Dog.prototype)<br>  Animal.call(this, name, energy)</pre><pre>  this.breed = breed<br>  // return this<br>}</pre><p>The reason Animal.prototype gets checked is because we overwrote Dog.prototype to delegate to Animal.prototype on failed lookups with this line:</p><pre>Dog.prototype = Object.create(Animal.prototype)</pre><p>Now one thing we haven’t talked about is what if Dog has its own methods? Well, that’s a simple solution. Just like with Animal, if we want to share a method across all instances of that class, we add it to the function’s prototype.</p><pre>... </pre><pre>function Dog (name, energy, breed) {<br>  Animal.call(this, name, energy)</pre><pre>this.breed = breed<br>}</pre><pre>Dog.prototype = Object.create(Animal.prototype)</pre><pre>Dog.prototype.bark = function () {<br>  console.log(&#39;Woof Woof!&#39;)<br>  this.energy -= .1<br>}</pre><p>👌 very nice. There’s just one small addition we need to make. If you remember back to the <a href="https://tylermcginnis.com/beginners-guide-to-javascript-prototype/">Beginner’s Guide to JavaScript’s Prototype</a> post, we were able to get access to the instances’ constructor function by using instance.constructor.</p><pre>function Animal (name, energy) {<br>  this.name = name<br>  this.energy = energy<br>}</pre><pre>const leo = new Animal(&#39;Leo&#39;, 7)<br>console.log(leo.constructor) // Logs the constructor function</pre><p>As explained in the previous post, “the reason this works is because any instances of Animal are going to delegate to Animal.prototype on failed lookups. So when you try to access leo.constructor, leo doesn’t have a constructor property so it will delegate that lookup to Animal.prototype which indeed does have a constructor property.”</p><p>The reason I bring this up is because in our implementation, we overwrote Dog.prototype with an object that delegates to Animal.prototype.</p><pre>function Dog (name, energy, breed) {<br>  Animal.call(this, name, energy)</pre><pre>  this.breed = breed<br>}</pre><pre>Dog.prototype = Object.create(Animal.prototype)</pre><pre>Dog.prototype.bark = function () {<br>  console.log(&#39;Woof Woof!&#39;)<br>  this.energy -= .1<br>}</pre><p>What that means is that now, any instances of Dog which log instance.constructor are going to get the Animal constructor rather than the Dog constructor. You can see for yourself by running this code:</p><pre>function Animal (name, energy) {<br>  this.name = name<br>  this.energy = energy<br>}</pre><pre>Animal.prototype.eat = function (amount) {<br>  console.log(`${this.name} is eating.`)<br>  this.energy += amount<br>}</pre><pre>Animal.prototype.sleep = function (length) {<br>  console.log(`${this.name} is sleeping.`)<br>  this.energy += length<br>}</pre><pre>Animal.prototype.play = function (length) {<br>  console.log(`${this.name} is playing.`)<br>  this.energy -= length<br>}</pre><pre>function Dog (name, energy, breed) {<br>  Animal.call(this, name, energy)</pre><pre>  this.breed = breed<br>}</pre><pre>Dog.prototype = Object.create(Animal.prototype)</pre><pre>Dog.prototype.bark = function () {<br>  console.log(&#39;Woof Woof!&#39;)<br>  this.energy -= .1<br>}</pre><pre>const charlie = new Dog(&#39;Charlie&#39;, 10, &#39;Goldendoodle&#39;)<br>console.log(charlie.constructor)</pre><p>Notice it gives you the Animal constructor even though charlie is a direct instance of Dog. Again, we can walk through what’s happening here just like we did above.</p><pre>const charlie = new Dog(&#39;Charlie&#39;, 10, &#39;Goldendoodle&#39;)<br>console.log(charlie.constructor)</pre><pre>/*<br>1) JavaScript checks if charlie has a constructor property - it doesn&#39;t.<br>2) JavaScript then checks if Dog.prototype has a constructor property<br>    - it doesn&#39;t because it was deleted when we overwrote Dog.prototype.<br>3) JavaScript then checks if Animal.prototype has a constructor property<br>    - it does so it logs that.<br>*/</pre><p>How can we fix this? Well, it’s pretty simple. We can just add the correct constructor property to Dog.prototype once we overwrite it.</p><pre>function Dog (name, energy, breed) {<br>  Animal.call(this, name, energy)</pre><pre>  this.breed = breed<br>}</pre><pre>Dog.prototype = Object.create(Animal.prototype)</pre><pre>Dog.prototype.bark = function () {<br>  console.log(&#39;Woof Woof!&#39;)<br>  this.energy -= .1<br>}</pre><pre>Dog.prototype.constructor = Dog</pre><p>At this point if we wanted to make another subclass, say Cat, we’d follow the same pattern.</p><pre>function Cat (name, energy, declawed) {<br>  Animal.call(this, name, energy)</pre><pre>  this.declawed = declawed<br>}</pre><pre>Cat.prototype = Object.create(Animal.prototype)<br>Cat.prototype.constructor = Cat</pre><pre>Cat.prototype.meow = function () {<br>  console.log(&#39;Meow!&#39;)<br>  this.energy -= .1<br>}</pre><p>This concept of having a base class with subclasses that delegate to it is called <strong>inheritance</strong> and it’s a staple of <strong>Object Oriented Programming (OOP)</strong>. If you’re coming from a different programming language, odds are you’re already familiar with OOP and inheritance.</p><p>Before ES6 classes, in JavaScript, inheritance was quite the task as you can see above. You need to understand now only <strong>when</strong> to use inheritance, but also a nice mix of .call, Object.create, this, and FN.prototype - all pretty advanced JS topics. Let’s see how we’d accomplish the same thing using ES6 classes though.</p><p>First, let’s review what it looks like to go from an ES5 “class” to an ES6 class using our Animal class.</p><pre>// ES5<br>function Animal (name, energy) {<br>  this.name = name<br>  this.energy = energy<br>}</pre><pre>Animal.prototype.eat = function (amount) {<br>  console.log(`${this.name} is eating.`)<br>  this.energy += amount<br>}</pre><pre>Animal.prototype.sleep = function (length) {<br>  console.log(`${this.name} is sleeping.`)<br>  this.energy += length<br>}</pre><pre>Animal.prototype.play = function (length) {<br>  console.log(`${this.name} is playing.`)<br>  this.energy -= length<br>}</pre><pre>const leo = new Animal(&#39;Leo&#39;, 7)</pre><pre>// ES6<br>class Animal {<br>  constructor(name, energy) {<br>    this.name = name<br>    this.energy = energy<br>  }<br>  eat(amount) {<br>    console.log(`${this.name} is eating.`)<br>    this.energy += amount<br>  }<br>  sleep() {<br>    console.log(`${this.name} is sleeping.`)<br>    this.energy += length<br>  }<br>  play() {<br>    console.log(`${this.name} is playing.`)<br>    this.energy -= length<br>  }<br>}</pre><pre>const leo = new Animal(&#39;Leo&#39;, 7)</pre><p>Now that we’ve refactored our Animal constructor function into an ES6 class, the next thing we need to do is figure out how to refactor our base class (Dog). The good news is it’s much more intuitive. For reference, in ES5, here’s what we had.</p><pre>function Dog (name, energy, breed) {<br>  Animal.call(this, name, energy)</pre><pre>  this.breed = breed<br>}</pre><pre>Dog.prototype = Object.create(Animal.prototype)</pre><pre>Dog.prototype.bark = function () {<br>  console.log(&#39;Woof Woof!&#39;)<br>  this.energy -= .1<br>}</pre><pre>Dog.prototype.constructor = Dog</pre><p>Before we get into inheritance, let’s refactor Dog to use an ES6 class as we learned in a previous post.</p><pre>class Dog {<br>  constructor(name, energy, breed) {<br>    this.breed = breed<br>  }<br>  bark() {<br>    console.log(&#39;Woof Woof!&#39;)<br>    this.energy -= .1<br>  }<br>}</pre><p>Looks great. Now, let’s figure out how to make sure that Dog inherits from Animal. The first step we need to make is a pretty straight forward one. With ES6 classes, you can extend a base class with this syntax:</p><pre>class Subclass extends Baseclass {}</pre><p>Translated into our example, that would make our Dog class look like this:</p><pre>class Animal {<br>  constructor(name, energy) {<br>    this.name = name<br>    this.energy = energy<br>  }<br>  eat(amount) {<br>    console.log(`${this.name} is eating.`)<br>    this.energy += amount<br>  }<br>  sleep() {<br>    console.log(`${this.name} is sleeping.`)<br>    this.energy += length<br>  }<br>  play() {<br>    console.log(`${this.name} is playing.`)<br>    this.energy -= length<br>  }<br>}</pre><pre>class Dog extends Animal {<br>  constructor(name, energy, breed) {<br>    this.breed = breed<br>  }<br>  bark() {<br>    console.log(&#39;Woof Woof!&#39;)<br>    this.energy -= .1<br>  }<br>}</pre><p>In ES5, in order to make sure that every instance of Dog had a name and an energy property, we used .call in order to invoke the Animal constructor function in the context of the Dog instance. Luckily for us, in ES6 it’s much more straight forward. Whenever you are extending a baseclass and you need to invoke that baseclass’ constructor function, you invoke super passing it any arguments it needs. So in our example, our Dog constructor gets refactored to look like this:</p><pre>class Animal {<br>  constructor(name, energy) {<br>    this.name = name<br>    this.energy = energy<br>  }<br>  eat(amount) {<br>    console.log(`${this.name} is eating.`)<br>    this.energy += amount<br>  }<br>  sleep() {<br>    console.log(`${this.name} is sleeping.`)<br>    this.energy += length<br>  }<br>  play() {<br>    console.log(`${this.name} is playing.`)<br>    this.energy -= length<br>  }<br>}</pre><pre>class Dog extends Animal {<br>  constructor(name, energy, breed) {<br>    super(name, energy) // calls Animal&#39;s constructor</pre><pre>    this.breed = breed<br>  }<br>  bark() {<br>    console.log(&#39;Woof Woof!&#39;)<br>    this.energy -= .1<br>  }<br>}</pre><p>And that’s it. No using .call, no using Object.create, no worrying about resetting constructor on the prototype - just extends the baseclass and make sure to call super.</p><p>What’s interesting about JavaScript is the same patterns you’ve learned these last few posts are directly caked into the language itself. Previously you learned that the reason all instances of Array have access to the array methods like pop, slice, filter, etc are because all of those methods live on Array.prototype.</p><pre>console.log(Array.prototype)</pre><pre>/*<br>  concat: ƒn concat()<br>  constructor: ƒn Array()<br>  copyWithin: ƒn copyWithin()<br>  entries: ƒn entries()<br>  every: ƒn every()<br>  fill: ƒn fill()<br>  filter: ƒn filter()<br>  find: ƒn find()<br>  findIndex: ƒn findIndex()<br>  forEach: ƒn forEach()<br>  includes: ƒn includes()<br>  indexOf: ƒn indexOf()<br>  join: ƒn join()<br>  keys: ƒn keys()<br>  lastIndexOf: ƒn lastIndexOf()<br>  length: 0n<br>  map: ƒn map()<br>  pop: ƒn pop()<br>  push: ƒn push()<br>  reduce: ƒn reduce()<br>  reduceRight: ƒn reduceRight()<br>  reverse: ƒn reverse()<br>  shift: ƒn shift()<br>  slice: ƒn slice()<br>  some: ƒn some()<br>  sort: ƒn sort()<br>  splice: ƒn splice()<br>  toLocaleString: ƒn toLocaleString()<br>  toString: ƒn toString()<br>  unshift: ƒn unshift()<br>  values: ƒn values()<br>*/</pre><p>You also learned that the reason all instances of Object have access to methods like hasOwnProperty and toString is because those methods live on Object.prototype.</p><pre>console.log(Object.prototype)</pre><pre>/*<br>  constructor: ƒn Object()<br>  hasOwnProperty: ƒn hasOwnProperty()<br>  isPrototypeOf: ƒn isPrototypeOf()<br>  propertyIsEnumerable: ƒn propertyIsEnumerable()<br>  toLocaleString: ƒn toLocaleString()<br>  toString: ƒn toString()<br>  valueOf: ƒn valueOf()<br>*/</pre><p>Here’s a challenge for you. With the list of Array methods and Object methods above, why does this code below work?</p><pre>const friends = [&#39;Mikenzi&#39;, &#39;Jake&#39;, &#39;Ean&#39;]</pre><pre>friends.hasOwnProperty(&#39;push&#39;) // false</pre><p>If you look at Array.prototype, there isn’t a hasOwnProperty method. Well if there isn’t a hasOwnProperty method located on Array.prototype, how does the friends array in the example above have access to hasOwnProperty?</p><p>The reason for that is because the Array class extends the Object class. So in our example above, when JavaScript sees that friends doesn’t have a hasOwnProperty property, it checks if Array.prototype does. When Array.prototype doesn’t, it checks if Object.prototype does, then it invokes it. It’s the same process we’ve seen throughout this blog post.</p><p>JavaScript has two types — <strong>Primitive</strong> types and <strong>Reference</strong> types.</p><p>Primitive types are boolean, number, string, null, and undefined and are immutable. Everything else is a reference type and they all extend Object.prototype. That’s why you can add properties to functions and arrays and that’s why both functions and arrays have access to the methods located on Object.prototype.</p><pre>function speak(){}<br>speak.woahFunctionsAreLikeObjects = true<br>console.log(speak.woahFunctionsAreLikeObjects) // true</pre><pre>const friends = [&#39;Mikenzi&#39;, &#39;Jake&#39;, &#39;Ean&#39;]<br>friends.woahArraysAreLikeObjectsToo = true<br>console.log(friends.woahArraysAreLikeObjectsToo) // true</pre><p>This was originally published at <a href="https://tylermcginnis.com/javascript-inheritance-and-the-prototype-chain/">TylerMcGinnis.com</a> and is part of their <a href="https://tylermcginnis.com/courses/advanced-javascript/">Advanced JavaScript</a> course.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d4298619bdae" width="1" height="1" alt=""><hr><p><a href="https://medium.com/free-code-camp/javascript-inheritance-and-the-prototype-chain-d4298619bdae">JavaScript Inheritance and the Prototype Chain</a> was originally published in <a href="https://medium.com/free-code-camp">We’ve moved to freeCodeCamp.org/news</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to validate an email address in JavaScript]]></title>
            <link>https://medium.com/swlh/how-to-validate-an-email-address-in-javascript-78d33f87f5c6?source=rss-c52389e3ee63------2</link>
            <guid isPermaLink="false">https://medium.com/p/78d33f87f5c6</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[email]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[regex]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Tyler McGinnis]]></dc:creator>
            <pubDate>Thu, 06 Dec 2018 17:41:44 GMT</pubDate>
            <atom:updated>2018-12-07T06:40:04.610Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RIlAvwZNN7D_2dsY6ccBxQ.jpeg" /></figure><p>Email validation is hard. With the vast amount of complex, but valid email addresses that exist today, the only way to truly tell if an email address is valid is to send the email and see if it bounces. With that said, there are a few things we can do on the front end to make the experience better for everyone. In this post, we’ll talk about a few common approaches for validating email addresses in JavaScript.</p><p>First, when validating email addresses I believe it’s better to error on the permissive side. I’d much rather let pass a few fake email addresses than reject a valid one. Front-end email validation is about figuring out if the syntax is correct, not if the email address is valid. With that said, we’ll start off with the most permissive solution and work our way towards the other end.</p><pre>function emailIsValid (email) {<br>  return /\S+@\S+\.\S+/.test(email)<br>}</pre><p>If you’re not familiar with RegEx, “/\S+@\S+\.\S+/” is testing for the most basic email address structure, &quot;_@_._&quot;. That’s typically all I ever assume about an email address. If the email the user types it doesn’t follow that structure, odds are they made a typo.</p><p>One issue with the Regex above is it’ll fail on this format: “_@_@._”. To fix that, we can change up our Regex a bit.</p><pre>function emailIsValid (email) {<br>  return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)<br>}</pre><pre>emailIsValid(&#39;tyler@<a href="mailto:tyler@tylermcginnis.com">tyler@tylermcginnis.com</a>&#39;) // false<br>emailIsValid(&#39;<a href="mailto:tyler@tylermcginnis.com">tyler@tylermcginnis.com</a>&#39;) // true</pre><p>That’s it. Anything beyond this is going to be too opinionated. You could find some other solutions by googling around but I recommend re-thinking your approach if the above examples don’t work for you.</p><p><em>Originally published at </em><a href="https://tylermcginnis.com/validate-email-address-javascript/"><em>tylermcginnis.com</em></a><em>.</em></p><figure><a href="https://medium.com/swlh"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YqDjlKFwScoQYQ62DWEdig.png" /></a></figure><h4>This story is published in <a href="https://medium.com/swlh">The Startup</a>, Medium’s largest entrepreneurship publication followed by +396,714 people.</h4><h4>Subscribe to receive <a href="http://growthsupply.com/the-startup-newsletter/">our top stories here</a>.</h4><figure><a href="https://medium.com/swlh"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ouK9XR4xuNWtCes-TIUNAw.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78d33f87f5c6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/how-to-validate-an-email-address-in-javascript-78d33f87f5c6">How to validate an email address in JavaScript</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Evolution of Async JavaScript: From Callbacks, to Promises, to Async/Await]]></title>
            <link>https://medium.com/free-code-camp/the-evolution-of-async-javascript-from-callbacks-to-promises-to-async-await-e73b047f2f40?source=rss-c52389e3ee63------2</link>
            <guid isPermaLink="false">https://medium.com/p/e73b047f2f40</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[asyncawait]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Tyler McGinnis]]></dc:creator>
            <pubDate>Wed, 21 Nov 2018 08:58:56 GMT</pubDate>
            <atom:updated>2018-11-22T04:07:54.031Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uO6Ma94FMebeo9eY2MPN8g.png" /></figure><p><em>Note: This is part of my </em><a href="https://tylermcginnis.com/courses/advanced-javascript/"><em>Advanced JavaScript</em></a><em> course. If you enjoy this post, check it out.</em></p><p>One of my favorite sites is <a href="http://www.berkshirehathaway.com/">BerkshireHathaway.com</a> — it’s simple, effective, and has been doing its job well since it launched in 1997. Even more remarkable, over the last 20 years, there’s a good chance this site has never had a bug.</p><p>Why? Because it’s all static. It’s been pretty much the same since it launched over 20 years ago.</p><p>Turns out sites are pretty simple to build if you have all of your data up front. Unfortunately, most sites now days don’t. To compensate for this, we’ve invented “patterns” for handling fetching external data for our apps.</p><p>Like most things, these patterns each have tradeoffs that have changed over time. In this post we’ll break down the pros and cons of three of the most common patterns, Callbacks, Promises, and Async/Await and talk about their significance and progression from a historical context.</p><p>If you prefer to watch a video version of this post, you can view that here-</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FgB-OmN1egV8%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DgB-OmN1egV8&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FgB-OmN1egV8%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/7c1c923b29230460a4c108c7a88de924/href">https://medium.com/media/7c1c923b29230460a4c108c7a88de924/href</a></iframe><p>Let’s start with the OG of these data fetching patterns, Callbacks.</p><h3>Callbacks</h3><blockquote><em>I’m going to assume you know exactly 0 about callbacks. If I’m assuming wrong, just scroll down a bit.</em></blockquote><p>When I was first learning to program, it helped me to think about functions as machines. These machines can do anything you want them to. They can even accept input and return a value. Each machine has a button on it that you can press when you want the machine to run, ().</p><pre>function add (x, y) { <br>  return x + y <br>}</pre><pre>add(2,3)</pre><p>Whether <strong>I</strong> press the button, <strong>you</strong> press the button, or <strong>someone else</strong> presses the button doesn’t matter. Whenever the button is pressed, like it or not, the machine is going to run.</p><pre>function add (x, y) {<br>  return x + y<br>}</pre><pre>const me = add<br>const you = add<br>const someoneElse = add</pre><pre>me(2,3) // 5 - Press the button, run the machine.<br>you(2,3) // 5 - Press the button, run the machine.<br>someoneElse(2,3) // 5 - Press the button, run the machine.</pre><p>In the code above we assign the add function to three different variables, me, you, and someoneElse. It’s important to note that the original add and each of the variables we created are pointing to the same spot in memory. They’re literally the exact same thing under different names. So when we invoke me, you, or someoneElse, it’s as if we’re invoking add.</p><p>Now what if we take our add machine and pass it to another machine? Remember, it doesn’t matter who presses the () button, if it’s pressed, it’s going to run.</p><pre>function add (x, y) {<br>  return x + y<br>}</pre><pre>function addFive (x, addReference) {<br>  return addReference(x, 5) // 15 - Press the button, run the machine.<br>}</pre><pre>addFive(10, add) // 15</pre><p>Your brain might have got a little weird on this one, nothing new is going on here though. Instead of “pressing the button” on add, we pass add as an argument to addFive, rename it addReference, and then we “press the button” or invoke it.</p><p>This highlights some important concepts of the JavaScript language. First, just as you can pass a string or a number as an argument to a function, so too can you pass a reference to a function as an argument. When you do this the function you’re passing as an argument is called a <strong>callback</strong> function and the function you’re passing the callback function to is called a <strong>higher order function</strong>.</p><p>Because vocabulary is important, here’s the same code with the variables re-named to match the concepts they’re demonstrating.</p><pre>function add (x,y) {<br>  return x + y<br>}</pre><pre>function higherOrderFunction (x, callback) {<br>  return callback(x, 5)<br>}</pre><pre>higherOrderFunction(10, add)</pre><p>This pattern should look familiar, it’s everywhere. If you’ve ever used any of the JavaScript Array methods, you’ve used a callback. If you’ve ever used lodash, you’ve used a callback. If you’ve ever used jQuery, you’ve used a callback.</p><pre>[1,2,3].map((i) =&gt; i + 5)</pre><pre>_.filter([1,2,3,4], (n) =&gt; n % 2 === 0 );</pre><pre>$(&#39;#btn&#39;).on(&#39;click&#39;, () =&gt;<br>  console.log(&#39;Callbacks are everywhere&#39;)<br>)</pre><p>In general, there are two popular use cases for callbacks. The first, and what we see in the .map and _.filter examples, is a nice abstraction over turning one value into another. We say “Hey, here’s an array and a function. Go ahead and get me a new value based on the function I gave you”. The second, and what we see in the jQuery example, is delaying execution of a function until a particular time. “Hey, here’s this function. Go ahead and invoke it whenever the element with an id of btn is clicked.” It’s this second use case that we’re going to focus on, “delaying execution of a function until a particular time”.</p><p>Right now we’ve only looked at examples that are synchronous. As we talked about at the beginning of this post, most of the apps we build don’t have all the data they need up front. Instead, they need to fetch external data as the user interacts with the app. We’ve just seen how callbacks can be a great use case for this because, again, they allow you to “delay execution of a function until a particular time.”</p><p>It doesn’t take much imagination to see how we can adapt that sentence to work with data fetching. Instead of delaying execution of a function until <em>a particular time</em>, we can delay execution of a function <em>until we have the data we need</em>. Here’s probably the most popular example of this, jQuery’s getJSON method.</p><pre>// updateUI and showError are irrelevant.<br>// Pretend they do what they sound like.</pre><pre>const id = &#39;tylermcginnis&#39;</pre><pre>$.getJSON({<br>  url: `<a href="https://api.github.com/users/${id}`">https://api.github.com/users/${id}`</a>,<br>  success: updateUI,<br>  error: showError,<br>})</pre><p>We can’t update the UI of our app until we have the user’s data. So what do we do? We say, “Hey, here’s an object. If the request succeeds, go ahead and call success passing it the user’s data. If it doesn’t, go ahead and call error passing it the error object. You don’t need to worry about what each method does, just be sure to call them when you’re supposed to”. This is a perfect demonstration of using a callback for async requests.</p><p>At this point we’ve learned about what callbacks are and how they can be beneficial both in synchronous and asynchronous code. What we haven’t talked yet is the dark side of callbacks. Take a look at this code below. Can you tell what’s happening?</p><pre>// updateUI, showError, and getLocationURL are irrelevant.<br>// Pretend they do what they sound like.</pre><pre>const id = &#39;tylermcginnis&#39;</pre><pre>$(&quot;#btn&quot;).on(&quot;click&quot;, () =&gt; {<br>  $.getJSON({<br>    url: `<a href="https://api.github.com/users/${id}`">https://api.github.com/users/${id}`</a>,<br>    success: (user) =&gt; {<br>      $.getJSON({<br>        url: getLocationURL(user.location.split(&#39;,&#39;)),<br>        success (weather) {<br>          updateUI({<br>            user,<br>            weather: weather.query.results<br>          })<br>        },<br>        error: showError,<br>      })<br>    },<br>    error: showError<br>  })<br>})</pre><p>If it helps, you can play around with the <a href="https://codesandbox.io/s/v06mmo3j7l">live version here</a>.</p><p>Notice we’ve added a few more layers of callbacks. First we’re saying don’t run the initial AJAX request until the element with an id of btn is clicked. Once the button is clicked, we make the first request. If that request succeeds, we make a second request. If that request succeeds, we invoke the updateUI method passing it the data we got from both requests. Regardless of if you understood the code at first glance or not, objectively it’s much harder to read than the code before. This brings us to the topic of “Callback Hell.”</p><p>As humans, we naturally think sequentially. When you have nested callbacks inside of nested callbacks, it forces you out of your natural way of thinking. Bugs happen when there’s a disconnect between how your software is read and how you naturally think.</p><p>Like most solutions to software problems, a commonly prescribed approach for making “Callback Hell” easier to consume is to modularize your code.</p><pre>function getUser(id, onSuccess, onFailure) {<br>  $.getJSON({<br>    url: `<a href="https://api.github.com/users/${id}`">https://api.github.com/users/${id}`</a>,<br>    success: onSuccess,<br>    error: onFailure<br>  })<br>}</pre><pre>function getWeather(user, onSuccess, onFailure) {<br>  $.getJSON({<br>    url: getLocationURL(user.location.split(&#39;,&#39;)),<br>    success: onSuccess,<br>    error: onFailure,<br>  })<br>}</pre><pre>$(&quot;#btn&quot;).on(&quot;click&quot;, () =&gt; {<br>  getUser(&quot;tylermcginnis&quot;, (user) =&gt; {<br>    getWeather(user, (weather) =&gt; {<br>      updateUI({<br>        user,<br>        weather: weather.query.results<br>      })<br>    }, showError)<br>  }, showError)<br>})</pre><p>If it helps, you can play around with the <a href="https://codesandbox.io/s/m587rq0lox">live version here</a>.</p><p>OK, the function names help us understand what’s going on, but is it objectively “better”? Not by much. We’ve put a band-aid over the readability issue of Callback Hell. The problem still exists that we naturally think sequentially and, even with the extra functions, nested callbacks break us out of that sequential way of thinking.</p><p>The next issue of callbacks has to do with <a href="https://en.wikipedia.org/wiki/Inversion_of_control">inversion of control</a>. When you write a callback, you’re assuming that the program you’re giving the callback to is responsible and will call it when (and only when) it’s supposed to. You’re essentially inverting the control of your program over to another program. When you’re dealing with libraries like jQuery, lodash, or even vanilla JavaScript, it’s safe to assume that the callback function will be invoked at the correct time with the correct arguments. However, for many third party libraries, callback functions are the interface for how you interact with them. It’s entirely plausible that a third party library could, whether on purpose or accidentally, break how they interact with your callback.</p><pre>function criticalFunction () {<br>  // It&#39;s critical that this function<br>  // gets called and with the correct<br>  // arguments.<br>}</pre><pre>thirdPartyLib(criticalFunction)</pre><p>Since you’re not the one calling criticalFunction, you have 0 control over when and with what argument it’s invoked. <em>Most</em> of the time this isn’t an issue, but when it is, it’s a big one.</p><h3>Promises</h3><p>Have you ever been to a busy restaurant without a reservation? When this happens, the restaurant needs a way to get back in contact with you when a table opens up. Historically, they’d just take your name and yell it when your table was ready. Then, as naturally occurs, they decided to start getting fancy. One solution was, instead of taking your name, they’d take your number and text you once a table opened up. This allowed you to be out of yelling range but more importantly, it allowed them to target your phone with ads whenever they wanted.</p><p>Sound familiar? It should! OK, maybe it shouldn’t. It’s a metaphor for callbacks! <strong>Giving your number to a restaurant is just like giving a callback function to a third party service. You <em>expect</em> the restaurant to text you when a table opens up, just like you <em>expect</em> the third party service to invoke your function when and how they said they would.</strong> Once your number or callback function is in their hands though, you’ve lost all control.</p><p>Thankfully, there is another solution that exists. One that, by design, allows you to keep all the control. You’ve probably even experienced it before — it’s that little buzzer thing they give you. You know, this one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/0*hEz6wPcMjw1R7kRF.png" /></figure><p>If you’ve never used one before, the idea is simple. Instead of taking your name or number, they give you this device. When the device starts buzzing and glowing, your table is ready. You can still do whatever you’d like as you’re waiting for your table to open up, but now you don’t have to give up anything. In fact, it’s the exact opposite. <strong>They</strong> have to give <strong>you</strong> something. There is no inversion of control.</p><p>The buzzer will always be in one of three different states — pending, fulfilled, or rejected.</p><p>pending is the default, initial state. When they give you the buzzer, it’s in this state.</p><p>fulfilled is the state the buzzer is in when it’s flashing and your table is ready.</p><p>rejected is the state the buzzer is in when something goes wrong. Maybe the restaurant is about to close or they forgot someone rented out the restaurant for the night.</p><p>Again, the important thing to remember is that you, the receiver of the buzzer, have all the control. If the buzzer gets put into fulfilled, you can go to your table. If it gets put into fulfilled and you want to ignore it, cool, you can do that too. If it gets put into rejected, that sucks but you can go somewhere else to eat. If nothing ever happens and it stays in pending, you never get to eat but you’re not actually out anything.</p><p>Now that you’re a master of the restaurant buzzer thingy, let’s apply that knowledge to something that matters.</p><p><strong>If giving the restaurant your number is like giving them a callback function, receiving the little buzzy thing is like receiving what’s called a “Promise”.</strong></p><p>As always, let’s start with <strong>why</strong>. Why do Promises exist? They exist to make the complexity of making asynchronous requests more manageable. Exactly like the buzzer, a Promise can be in one of three states, pending, fulfilled or rejected. Unlike the buzzer, instead of these states representing the status of a table at a restaurant, they represent the status of an asynchronous request.</p><p>If the async request is still ongoing, the Promise will have a status of pending. If the async request was successfully completed, the Promise will change to a status of fulfilled. If the async request failed, the Promise will change to a status of rejected. The buzzer metaphor is pretty spot on, right?</p><p>Now that you understand why Promises exist and the different states they can be in, there are three more questions we need to answer.</p><ol><li>How do you create a Promise?</li><li>How do you change the status of a promise?</li><li>How do you listen for when the status of a promise changes?</li></ol><p>1) How do you create a Promise?</p><p>This one is pretty straight forward. You create a new instance of Promise.</p><pre>const promise = new Promise()</pre><p>2) How do you change the status of a promise?</p><p>The Promise constructor function takes in a single argument, a (callback) function. This function is going to be passed two arguments, resolve and reject.</p><p>resolve - a function that allows you to change the status of the promise to fulfilled</p><p>reject - a function that allows you to change the status of the promise to rejected.</p><p>In the code below, we use setTimeout to wait 2 seconds and then invoke resolve. This will change the status of the promise to fulfilled.</p><pre>const promise = new Promise((resolve, reject) =&gt; {<br>  setTimeout(() =&gt; {<br>    resolve() // Change status to &#39;fulfilled&#39;<br>  }, 2000)<br>})</pre><p>We can see this change in action by logging the promise right after we create it and then again roughly 2 seconds later after resolve has been called.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZCExMomFBiQihLQ-.gif" /></figure><p>Notice the promise goes from &lt;pending&gt; to &lt;resolved&gt;.</p><h4>3) How do you listen for when the status of a promise changes?</h4><p>In my opinion this is the most important question. It’s cool we know how to create a promise and change its status, but that’s worthless if we don’t know how to do anything after the status changes.</p><p>One thing we haven’t talked about yet is what a promise actually is. When you create a new Promise, you’re really just creating a plain old JavaScript object. This object can invoke two methods, then, and catch. Here’s the key. When the status of the promise changes to fulfilled, the function that was passed to .then will get invoked. When the status of a promise changes to rejected, the function that was passed to .catch will be invoked. What this means is that once you create a promise, you’ll pass the function you want to run if the async request is successful to .then. You’ll pass the function you want to run if the async request fails to .catch.</p><p>Let’s take a look at an example. We’ll use setTimeout again to change the status of the promise to fulfilled after two seconds (2000 milliseconds).</p><pre>function onSuccess () {<br>  console.log(&#39;Success!&#39;)<br>}</pre><pre>function onError () {<br>  console.log(&#39;💩&#39;)<br>}</pre><pre>const promise = new Promise((resolve, reject) =&gt; {<br>  setTimeout(() =&gt; {<br>    resolve()<br>  }, 2000)<br>})</pre><pre>promise.then(onSuccess)<br>promise.catch(onError)</pre><p>If you run the code above you’ll notice that roughly 2 seconds later, you’ll see “Success!” in the console. Again the reason this happens is because of two things. First, when we created the promise, we invoked resolve after ~2000 milliseconds - this changed the status of the promise to fulfilled. Second, we passed the onSuccess function to the promises’ .then method. By doing that we told the promise to invoke onSuccess when the status of the promise changed to fulfilled which it did after ~2000 milliseconds.</p><p>Now let’s pretend something bad happened and we wanted to change the status of the promise to rejected. Instead of calling resolve, we would call reject.</p><pre>function onSuccess () {<br>  console.log(&#39;Success!&#39;)<br>}</pre><pre>function onError () {<br>  console.log(&#39;💩&#39;)<br>}</pre><pre>const promise = new Promise((resolve, reject) =&gt; {<br>  setTimeout(() =&gt; {<br>    reject()<br>  }, 2000)<br>})</pre><pre>promise.then(onSuccess)<br>promise.catch(onError)</pre><p>Now this time instead of the onSuccess function being invoked, the onError function will be invoked since we called reject.</p><p>Now that you know your way around the Promise API, let’s start looking at some real code.</p><p>Remember the last async callback example we saw earlier?</p><pre>function getUser(id, onSuccess, onFailure) {<br>  $.getJSON({<br>    url: `<a href="https://api.github.com/users/${id}`">https://api.github.com/users/${id}`</a>,<br>    success: onSuccess,<br>    error: onFailure<br>  })<br>}</pre><pre>function getWeather(user, onSuccess, onFailure) {<br>  $.getJSON({<br>    url: getLocationURL(user.location.split(&#39;,&#39;)),<br>    success: onSuccess,<br>    error: onFailure,<br>  })<br>}</pre><pre>$(&quot;#btn&quot;).on(&quot;click&quot;, () =&gt; {<br>  getUser(&quot;tylermcginnis&quot;, (user) =&gt; {<br>    getWeather(user, (weather) =&gt; {<br>      updateUI({<br>        user,<br>        weather: weather.query.results<br>      })<br>    }, showError)<br>  }, showError)<br>})</pre><p>Is there anyway we could use the Promise API here instead of using callbacks? What if we wrap our AJAX requests inside of a promise? Then we can simply resolve or reject depending on how the request goes. Let’s start with getUser.</p><pre>function getUser(id) {<br>  return new Promise((resolve, reject) =&gt; {<br>    $.getJSON({<br>      url: `<a href="https://api.github.com/users/${id}`">https://api.github.com/users/${id}`</a>,<br>      success: resolve,<br>      error: reject<br>    })<br>  })<br>}</pre><p>Nice. Notice that the parameters of getUser have changed. Instead of receiving id, onSuccess, and onFailure, it just receives id. There’s no more need for those other two callback functions because we’re no longer inverting control. Instead, we use the Promise’s resolve and reject functions. resolve will be invoked if the request was successful, reject will be invoked if there was an error.</p><p>Next let’s refactor getWeather. We’ll follow the same strategy here. Instead of taking in onSuccess and onFailure callback functions, we’ll use resolve and reject.</p><pre>function getWeather(user) {<br>  return new Promise((resolve, reject) =&gt; {<br>    $.getJSON({<br>      url: getLocationURL(user.location.split(&#39;,&#39;)),<br>      success: resolve,<br>      error: reject,<br>    })<br>  })<br>}</pre><p>Looking good. Now the last thing we need to update is our click handler. Remember, here’s the flow we want to take.</p><ol><li>Get the user’s information from the Github API.</li><li>Use the user’s location to get their weather from the Yahoo Weather API.</li><li>Update the UI with the users info and their weather.</li></ol><p>Let’s start with #1 — getting the user’s information from the Github API.</p><pre>$(&quot;#btn&quot;).on(&quot;click&quot;, () =&gt; {<br>  const userPromise = getUser(&#39;tylermcginnis&#39;)</pre><pre>userPromise.then((user) =&gt; {</pre><pre>})</pre><pre>userPromise.catch(showError)<br>})</pre><p>Notice that now instead of getUser taking in two callback functions, it returns us a promise that we can call .then and .catch on. If .then is called, it’ll be called with the user’s information. If .catch is called, it’ll be called with the error.</p><p>Next let’s do #2 — Use the user’s location to get their weather.</p><pre>$(&quot;#btn&quot;).on(&quot;click&quot;, () =&gt; {<br>  const userPromise = getUser(&#39;tylermcginnis&#39;)</pre><pre>userPromise.then((user) =&gt; {<br>    const weatherPromise = getWeather(user)<br>    weatherPromise.then((weather) =&gt; {</pre><pre>})</pre><pre>weatherPromise.catch(showError)<br>  })</pre><pre>userPromise.catch(showError)<br>})</pre><p>Notice we follow the exact same pattern we did in #1 but now we invoke getWeather passing it the user object we got from userPromise.</p><p>Finally, #3 — Update the UI with the users info and their weather.</p><pre>$(&quot;#btn&quot;).on(&quot;click&quot;, () =&gt; {<br>  const userPromise = getUser(&#39;tylermcginnis&#39;)</pre><pre>userPromise.then((user) =&gt; {<br>    const weatherPromise = getWeather(user)<br>    weatherPromise.then((weather) =&gt; {<br>      updateUI({<br>        user,<br>        weather: weather.query.results<br>      })<br>    })</pre><pre>weatherPromise.catch(showError)<br>  })</pre><pre>userPromise.catch(showError)<br>})</pre><p><a href="https://codesandbox.io/s/l9xrjq88p7">Here’s the full code</a> you can play around with.</p><p>Our new code is <em>better</em>, but there are still some improvement we can make. Before we can make those improvements though, there are two more features of promises you need to be aware of, chaining and passing arguments from resolve to then.</p><h4>Chaining</h4><p>Both .then and .catch will return a new promise. That seems like a small detail but it’s important because it means that promises can be chained.</p><p>In the example below, we call getPromise which returns us a promise that will resolve in at least 2000 milliseconds. From there, because .then will return a promise, we can continue to chain our .thens together until we throw a new Error which is caught by the .catch method.</p><pre>function getPromise () {<br>  return new Promise((resolve) =&gt; {<br>    setTimeout(resolve, 2000)<br>  })<br>}</pre><pre>function logA () {<br>  console.log(&#39;A&#39;)<br>}</pre><pre>function logB () {<br>  console.log(&#39;B&#39;)<br>}</pre><pre>function logCAndThrow () {<br>  console.log(&#39;C&#39;)</pre><pre>throw new Error()<br>}</pre><pre>function catchError () {<br>  console.log(&#39;Error!&#39;)<br>}</pre><pre>getPromise()<br>  .then(logA) // A<br>  .then(logB) // B<br>  .then(logCAndThrow) // C<br>  .catch(catchError) // Error!</pre><p>Cool, but why is this so important? Remember back in the callback section we talked about one of the downfalls of callbacks being that they force you out of your natural, sequential way of thinking. When you chain promises together, it doesn’t force you out of that natural way of thinking because chained promises are sequential. getPromise runs then logA runs then logB runs then....</p><p>Just so you can see one more example, here’s a common use case when you use the fetch API. fetch will return you a promise that will resolve with the HTTP response. To get the actual JSON, you’ll need to call .json. Because of chaining, we can think about this in a sequential manner.</p><pre>fetch(&#39;/api/user.json&#39;)<br>  .then((response) =&gt; response.json())<br>  .then((user) =&gt; {<br>    // user is now ready to go.<br>  })</pre><p>Now that we know about chaining, let’s refactor our getUser/getWeather code from earlier to use it.</p><pre>function getUser(id) {<br>  return new Promise((resolve, reject) =&gt; {<br>    $.getJSON({<br>      url: `<a href="https://api.github.com/users/${id}`">https://api.github.com/users/${id}`</a>,<br>      success: resolve,<br>      error: reject<br>    })<br>  })<br>}</pre><pre>function getWeather(user) {<br>  return new Promise((resolve, reject) =&gt; {<br>    $.getJSON({<br>      url: getLocationURL(user.location.split(&#39;,&#39;)),<br>      success: resolve,<br>      error: reject,<br>    })<br>  })<br>}</pre><pre>$(&quot;#btn&quot;).on(&quot;click&quot;, () =&gt; {<br>  getUser(&quot;tylermcginnis&quot;)<br>    .then(getWeather)<br>    .then((weather) =&gt; {<br>      // We need both the user and the weather here.<br>      // Right now we just have the weather<br>      updateUI() // ????<br>    })<br>    .catch(showError)<br>})</pre><p>It <em>looks</em> much better, but now we’re running into an issue. Can you spot it? In the second .then we want to to call updateUI. The problem is we need to pass updateUI both the user and the weather. Currently how we have it set up, we’re only receiving the weather, not the user. Somehow we need to figure out a way to make it so the promise that getWeather returns is resolved with both the user and the weather.</p><p>Here’s the key. resolve is just a function. Any arguments you pass to it will be passed along to the function given to .then. What that means is that inside of getWeather, if we invoke resolve ourself, we can pass to it weather and user. Then, the second .then method in our chain will receive both user and weather as an argument.</p><pre>function getWeather(user) {<br>  return new Promise((resolve, reject) =&gt; {<br>    $.getJSON({<br>      url: getLocationURL(user.location.split(&#39;,&#39;)),<br>      success(weather) {<br>        resolve({ user, weather: weather.query.results })<br>      },<br>      error: reject,<br>    })<br>  })<br>}</pre><pre>$(&quot;#btn&quot;).on(&quot;click&quot;, () =&gt; {<br>  getUser(&quot;tylermcginnis&quot;)<br>    .then(getWeather)<br>    .then((data) =&gt; {<br>      // Now, data is an object with a<br>      // &quot;weather&quot; property and a &quot;user&quot; property.</pre><pre>updateUI(data)<br>    })<br>    .catch(showError)<br>})</pre><blockquote><em>You can play around with the </em><a href="https://codesandbox.io/s/9lkl75vqxw"><em>final code here</em></a></blockquote><p>It’s in our click handler where you really see the power of promises shine compared to callbacks.</p><pre>// Callbacks 🚫<br>getUser(&quot;tylermcginnis&quot;, (user) =&gt; {<br>  getWeather(user, (weather) =&gt; {<br>    updateUI({<br>      user,<br>      weather: weather.query.results<br>    })<br>  }, showError)<br>}, showError)</pre><pre>// Promises ✅<br>getUser(&quot;tylermcginnis&quot;)<br>  .then(getWeather)<br>  .then((data) =&gt; updateUI(data))<br>  .catch(showError);</pre><p>Following that logic feels natural because it’s how we’re used to thinking, sequentially. getUser then getWeather then update the UI with the data.</p><p>Now it’s clear that promises drastically increase the readability of our asynchronous code, but is there a way we can make it even better? Assume that you were on the TC39 committee and you had all the power to add new features to the JavaScript language. What steps, if any, would you take to improve this code?</p><pre>$(&quot;#btn&quot;).on(&quot;click&quot;, () =&gt; {<br>  getUser(&quot;tylermcginnis&quot;)<br>    .then(getWeather)<br>    .then((data) =&gt; updateUI(data))<br>    .catch(showError)<br>})</pre><p>As we’ve discussed, the code reads pretty nicely. Just as our brains work, it’s in a sequential order. One issue that we did run into was that we needed to thread the data (users) from the first async request all the way through to the last .then. This wasn’t a big deal, but it made us change up our getWeather function to also pass along users. What if we just wrote our asynchronous code the same way which we write our synchronous code? If we did, that problem would go away entirely and it would still read sequentially. Here’s an idea.</p><pre>$(&quot;#btn&quot;).on(&quot;click&quot;, () =&gt; {<br>  const user = getUser(&#39;tylermcginnis&#39;)<br>  const weather = getWeather(user)</pre><pre>updateUI({<br>    user,<br>    weather,<br>  })<br>})</pre><p>Well, that would be nice. Our asynchronous code looks exactly like our synchronous code. There’s no extra steps our brain needs to take because we’re already very familiar with this way of thinking. Sadly, this obviously won’t work. As you know, if we were to run the code above, user and weather would both just be promises since that’s what getUser and getWeather return. But remember, we’re on TC39. We have all the power to add any feature to the language we want. As is, this code would be really tricky to make work. We’d have to somehow teach the JavaScript engine to know the difference between asynchronous function invocations and regular, synchronous function invocations on the fly. Let’s add a few keywords to our code to make it easier on the engine.</p><p>First, let’s add a keyword to the main function itself. This could clue the engine to the fact that inside of this function, we’re going to have some asynchronous function invocations. Let’s use async for this.</p><pre>$(&quot;#btn&quot;).on(&quot;click&quot;, async () =&gt; {<br>  const user = getUser(&#39;tylermcginnis&#39;)<br>  const weather = getWeather(user)</pre><pre>updateUI({<br>    user,<br>    weather,<br>  })<br>})</pre><p>Cool. That seems reasonable. Next let’s add another keyword to let the engine know exactly when a function being invoked is asynchronous and is going to return a promise. Let’s use await. As in, “Hey engine. This function is asynchronous and returns a promise. Instead of continuing on like you typically do, go ahead and ‘await’ the eventual value of the promise and return it before continuing”. With both of our new async and await keywords in play, our new code will look like this.</p><pre>$(&quot;#btn&quot;).on(&quot;click&quot;, async () =&gt; {<br>  const user = await getUser(&#39;tylermcginnis&#39;)<br>  const weather = await getWeather(user.location)</pre><pre>updateUI({<br>    user,<br>    weather,<br>  })<br>})</pre><p>Pretty slick. We’ve invented a reasonable way to have our asynchronous code look and behave as if it were synchronous. Now the next step is to actually convince someone on TC39 that this is a good idea. Lucky for us, as you probably guessed by now, we don’t need to do any convincing because this feature is already part of JavaScript and it’s called Async/Await.</p><p>Don’t believe me? <a href="https://codesandbox.io/s/00w10o19xn">Here’s our live code now</a> that we’ve added Async/Await to it. Feel free to play around with it.</p><h4>async functions return a promise</h4><p>Now that you’ve seen the benefit of Async/Await, let’s discuss some smaller details that are important to know. First, anytime you add async to a function, that function is going to implicitly return a promise.</p><pre>async function getPromise(){}</pre><pre>const promise = getPromise()</pre><p>Even though getPromise is literally empty, it’ll still return a promise since it was an async function.</p><p>If the async function returns a value, that value will also get wrapped in a promise. That means you’ll have to use .then to access it.</p><pre>async function add (x, y) {<br>  return x + y<br>}</pre><pre>add(2,3).then((result) =&gt; {<br>  console.log(result) // 5<br>})</pre><h4>await without async is bad</h4><p>If you try to use the await keyword inside of a function that isn’t async, you’ll get an error.</p><pre>$(&quot;#btn&quot;).on(&quot;click&quot;, () =&gt; {<br>  const user = await getUser(&#39;tylermcginnis&#39;) // SyntaxError: await is a reserved word<br>  const weather = await getWeather(user.location) // SyntaxError: await is a reserved word</pre><pre>updateUI({<br>    user,<br>    weather,<br>  })<br>})</pre><p>Here’s how I think about it. When you add async to a function it does two things. It makes it so the function itself returns (or wraps what gets returned in) a promise and makes it so you can use await inside of it.</p><h4>Error Handling</h4><p>You may have noticed we cheated a little bit. In our original code we had a way to catch any errors using .catch. When we switched to Async/Await, we removed that code. With Async/Await, the most common approach is to wrap your code in a try/catch block to be able to catch the error.</p><pre>$(&quot;#btn&quot;).on(&quot;click&quot;, async () =&gt; {<br>  try {<br>    const user = await getUser(&#39;tylermcginnis&#39;)<br>    const weather = await getWeather(user.location)</pre><pre>updateUI({<br>      user,<br>      weather,<br>    })<br>  } catch (e) {<br>    showError(e)<br>  }<br>})</pre><p>This post was originally published at <a href="https://tylermcginnis.com/async-javascript-from-callbacks-to-promises-to-async-await/">tylermcginnis.com</a> and is part of my <a href="https://tylermcginnis.com/courses/advanced-javascript">Advanced JavaScript</a> course. <a href="http://twitter.com/tylermcginnis">Connect with me on Twitter!</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e73b047f2f40" width="1" height="1" alt=""><hr><p><a href="https://medium.com/free-code-camp/the-evolution-of-async-javascript-from-callbacks-to-promises-to-async-await-e73b047f2f40">The Evolution of Async JavaScript: From Callbacks, to Promises, to Async/Await</a> was originally published in <a href="https://medium.com/free-code-camp">We’ve moved to freeCodeCamp.org/news</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>