<?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:media="http://search.yahoo.com/mrss/"><channel><title><![CDATA[Ben Comeau | Blog]]></title><description><![CDATA[Snackable programming thoughts and tips]]></description><link>https://blog.bencomeau.dev/</link><image><url>https://blog.bencomeau.dev/favicon.png</url><title>Ben Comeau | Blog</title><link>https://blog.bencomeau.dev/</link></image><generator>Ghost 2.16</generator><lastBuildDate>Fri, 10 Apr 2026 02:50:30 GMT</lastBuildDate><atom:link href="https://blog.bencomeau.dev/rss/" rel="self" type="application/rss+xml"/><ttl>60</ttl><item><title><![CDATA[Docker: Hot Reloading React and Express]]></title><description><![CDATA[There is little doubt that Docker has improved developer experience over the years but it's also easy to argue that continually rebuilding images to pull in changes takes away from developer experience. Let's look at introducing hot reloading in our docker flow!]]></description><link>https://blog.bencomeau.dev/docker-hot-reloading/</link><guid isPermaLink="false">5dba4b8b1961373a2fc10524</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Node]]></category><category><![CDATA[React]]></category><category><![CDATA[Tooling]]></category><dc:creator><![CDATA[Ben Comeau]]></dc:creator><pubDate>Sat, 25 May 2019 19:41:00 GMT</pubDate><media:content url="https://blog.bencomeau.dev/content/images/2019/10/docker-hot-reload.png" medium="image"/><content:encoded><![CDATA[<img src="https://blog.bencomeau.dev/content/images/2019/10/docker-hot-reload.png" alt="Docker: Hot Reloading React and Express"><p>There is little doubt that Docker has improved developer experience over the years but it's also easy to argue that continually rebuilding images to pull in changes takes away from developer experience. So let's look at how we can introduce hot reloading in our React and Express apps, using Docker.</p><blockquote>Important: this is great for development but should <strong>not</strong> be used in production!</blockquote><p>First, this will be our directory structure, where <code>client</code> is a React app, and <code>server</code> is an Express app:</p><!--kg-card-begin: markdown--><pre><code class="language-js">|client
|--Dockerfile
|
|server
|--Dockerfile
|
|-docker-compose.yml
</code></pre>
<!--kg-card-end: markdown--><p></p><p>Next, let's install React, Express, and create our necessary docker files. Since our focus is on introducing hot reloading, we'll just use generators to create our apps:</p><!--kg-card-begin: markdown--><pre><code class="language-js">npx create-react-app client
npx express-generator --no-view server // No need for views in this example
touch client/Dockerfile
touch server/Dockerfile
touch docker-compose.yml
</code></pre>
<!--kg-card-end: markdown--><p></p><p>We'll want to add <code>nodemon</code> as a dev dependency to our Express app, in order to introduce automatic reloading:</p><!--kg-card-begin: markdown--><pre><code class="language-js">// Do this within the server directory
yarn add -D nodemon
</code></pre>
<!--kg-card-end: markdown--><p></p><p>And we'll need to update <code>server/package.json</code> to ensure <code>nodemon</code> is used to start our app:</p><!--kg-card-begin: markdown--><pre><code class="language-js">&quot;scripts&quot;: {
  &quot;start&quot;: &quot;nodemon ./bin/www&quot; // Changed from node -&gt; nodemon
},
</code></pre>
<!--kg-card-end: markdown--><p></p><p>As well as <code>server/bin/www</code> to use port <code>3001</code>:</p><!--kg-card-begin: markdown--><pre><code class="language-js">var port = normalizePort(process.env.PORT || 3001);
</code></pre>
<!--kg-card-end: markdown--><p></p><p>In order to proxy requests to the API, we'll need to add the <code>proxy</code> property in our <code>client/package.json</code> file:</p><!--kg-card-begin: markdown--><pre><code>{
  ...
  &quot;proxy&quot;: &quot;http://server:3001&quot;,
  ...
}
</code></pre>
<!--kg-card-end: markdown--><p></p><blockquote>The value of <code>server</code> will resolve to the container's IP, thanks to Docker's bridge networking.</blockquote><p>Great, now we can add content to our Dockerfile(s):</p><!--kg-card-begin: markdown--><pre><code class="language-js">// client/Dockerfile
FROM node
WORKDIR /usr/src/client
COPY package.json .
RUN yarn install
COPY src ./src
COPY public ./public
EXPOSE 3000
CMD [ &quot;yarn&quot;, &quot;start&quot; ]

// server/Dockerfile
FROM node
WORKDIR /usr/src/server
COPY package.json .
RUN yarn install
COPY . .
EXPOSE 3001
CMD [ &quot;yarn&quot;, &quot;start&quot; ]
</code></pre>
<!--kg-card-end: markdown--><p></p><p>The above is a pretty standard setup for Dockerfiles; we're using a node image, setting our working directory, copying the necessary files, exposing the port, and setting the entry command.</p><p>To orchestrate building these images, we'll need to setup our <code>docker-compose.yml</code> file:</p><!--kg-card-begin: markdown--><pre><code class="language-js">version: '3'
services:
  client:
    build: client
    ports:
      - &quot;3000:3000&quot;
    restart: always
    command: yarn start
    volumes: # This is where the magic happens!
      - ./client/src:/usr/src/client/src
      - ./client/public:/usr/src/client/public
  server:
    build: server
    ports:
      - &quot;3001:3001&quot;
    restart: always
    command: yarn start
    volumes: # This is where the magic happens!
      - ./server:/usr/src/server
      - /usr/src/server/node_modules/
</code></pre>
<!--kg-card-end: markdown--><p></p><p>The key part above is the <code>volumes</code> setting; this binds your local files into your docker container. So looking at the line <code>./client/src:/usr/src/client/src</code>, we can see that all local files under <code>src</code> will be bound into your container's <code>src</code> directory. The power is that if you make a change locally, it's persisted to your container, which those files are being watched and thus it triggers the hot reload.</p><p>Alright, we should be all set! Let's give it a try by running:</p><!--kg-card-begin: markdown--><pre><code class="language-js">docker-compose up
</code></pre>
<!--kg-card-end: markdown--><p></p><p>Once docker builds the images and kicks off the containers, you will be able to access the client application at <a href="http://localhost:3000">http://localhost:3000</a>. To confirm hot reloading is working, we can make a small change in <code>client/src/App.js</code> and watch the changes automatically take place in our browser. Similarly, we can add a route to our Express server and it'll be made available immediately thanks to nodemon.</p><blockquote>It's important to note that changing files <strong>outside</strong> those bound via our <code>volumes</code> mount will <strong>not</strong> be reflected until the image is rebuilt. In other words, hot reloading will only care about the files defined in our <code>volumes</code> definition within <code>docker-compose.yml</code>.</blockquote><p>That should be it! This approach makes working in docker much more streamlined and is a pattern which I often use.</p><p> </p>]]></content:encoded></item><item><title><![CDATA[React + TypeScript]]></title><description><![CDATA[Use React and TypeScript together to get code suggestion, error highlighting, and self-documenting components which allow one to build scalable software!]]></description><link>https://blog.bencomeau.dev/react-typescript/</link><guid isPermaLink="false">5d10ff2b1961373a2fc1040d</guid><category><![CDATA[React]]></category><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Ben Comeau]]></dc:creator><pubDate>Sat, 13 Apr 2019 16:13:00 GMT</pubDate><media:content url="https://blog.bencomeau.dev/content/images/2019/06/carbon-2-.png" medium="image"/><content:encoded><![CDATA[<img src="https://blog.bencomeau.dev/content/images/2019/06/carbon-2-.png" alt="React + TypeScript"><p>The more I use TypeScript, the more I come to like it – similarly this is how I feel about React! So I started using the two of them together to get code suggestions and error highlighting before transpile, but also self-documenting components which is a huge benefit. Let's look at a small example on how to get up and running with React and TypeScript.</p><p>There are a few ways to do this – for brevity we'll use the CRA method with the optional TypeScript flag. But you can also add TypeScript to an existing React app by <a href="https://facebook.github.io/create-react-app/docs/adding-typescript">requiring the necessary libraries</a>.</p><p><code>npx create-react-app todos-typescript --typescript</code></p><p>The first thing you'll notice is the <code>.js</code> extensions have been replaced with <code>.tsx</code> which is a TypeScript file type, with JSX in it (hence the "x").</p><p>In a new file <code>src/interfaces/Todo.ts</code>, let's create an interface to represent our <code>todo</code> object:</p><!--kg-card-begin: markdown--><pre><code class="language-javascript">// Notice it's a .ts file!
interface Todo {
    id: number,
    title: String,
    completed: Boolean
}

export default Todo
</code></pre>
<!--kg-card-end: markdown--><p></p><p>This will make our interface reusable throughout our tiny project. Now in our <code>App.tsx</code> file, let's create interfaces for our Props and State:</p><!--kg-card-begin: markdown--><pre><code class="language-javascript">import TodoInterface from './interfaces/Todo'

interface IProps {}

interface IState {
  todos: Array&lt;TodoInterface&gt; // This is the interface we created earlier!
}
</code></pre>
<!--kg-card-end: markdown--><p></p><p>Great! If you're new to TypeScript, this tells any component using the <code>state</code> object that the <code>todos</code> property is an array of objects, each containing an <code>id</code>, <code>title</code>, and <code>completed</code> property. How is that for self-documenting code?!</p><p>Next, we need to tell the <code>App</code> component that our state should adhere to this interface:</p><!--kg-card-begin: markdown--><pre><code class="language-javascript">class App extends React.Component&lt;IProps, IState&gt; { // Small change here!
  state = {
    todos: [
      {
        id: 1,
        title: 'Walk the dog',
        completed: 'no' // Let's make this a String on purpose
      }
    ]
  }

  render() {
    return (
      &lt;div className=&quot;App&quot;&gt;
        ...
      &lt;/div&gt;
    );
  }
}
</code></pre>
<!--kg-card-end: markdown--><p></p><p>Right away, we can see our IDE (if you have the <a href="https://code.visualstudio.com/docs/typescript/typescript-tutorial">correct extensions</a>) telling us that our state doesn't adhere to our interface:</p><!--kg-card-begin: image--><figure class="kg-card kg-image-card"><img src="https://blog.bencomeau.dev/content/images/2019/06/Screen-Shot-2019-06-24-at-10.19.10-AM.png" class="kg-image" alt="React + TypeScript"></figure><!--kg-card-end: image--><p></p><p>To mitigate this, just update<code>completed: 'no'</code> to <code>completed: false</code> so it's a Boolean value as expected.</p><p>Next, we'll create a new <code>Todos</code> component to which we'll pass our state as props. But instead of just trusting we've typed it correctly, we'll create the props interface and have TypeScript watch our back!</p><!--kg-card-begin: markdown--><pre><code class="language-javascript">import TodoInterface from './interfaces/Todo'

interface IProps {
    todos: Array&lt;TodoInterface&gt;
}

class Todos extends React.Component&lt;IProps&gt; { // Use the interface!
    render() {
        return this.props.todos.map(todo =&gt; {
            return (
                &lt;div&gt;
                    &lt;h3&gt;{todo.title}&lt;/h3&gt;
                    &lt;span&gt;Completed: {todo.completed ? 'Yes' : 'No'}&lt;/span&gt;
                &lt;/div&gt;
            )
        })
    }
}
</code></pre>
<!--kg-card-end: markdown--><p></p><p>Lastly, we can start our development server to view our terribly-basic Todo app which doesn't offer any interaction options but <em>does</em> have self-documenting, reliable code!</p><p>And that's it! Very small example of integrating two great libraries together – hopefully you can see the benefit in using them to write applications at scale!</p>]]></content:encoded></item><item><title><![CDATA[React Snippets in VS Code]]></title><description><![CDATA[The VS Code ES7 React/Redux/React-Native/JS Snippets extension is truly amazing. It allows for quick scaffolding with just a few taps of the keyboard!]]></description><link>https://blog.bencomeau.dev/react-snippets-in-vs-code/</link><guid isPermaLink="false">5d0eee651961373a2fc103b6</guid><category><![CDATA[React]]></category><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Ben Comeau]]></dc:creator><pubDate>Sun, 31 Mar 2019 03:34:00 GMT</pubDate><media:content url="https://blog.bencomeau.dev/content/images/2019/06/carbon-1-.png" medium="image"/><content:encoded><![CDATA[<img src="https://blog.bencomeau.dev/content/images/2019/06/carbon-1-.png" alt="React Snippets in VS Code"><p>I love finding out about nice shortcuts which make repeatable tasks quicker which is why I'm so happy to have found this VS Code extension.</p><p>The <em>VS Code ES7 React/Redux/React-Native/JS snippets</em> extension is super powerful; it quickly and intuitively writes out snippets with just a taps on the keyboard. The list of options is exhaustive (in a good way!), so I'll just share the couple I'm finding most useful at the moment.</p><p><code>rce</code> will create a React Component using the filename as the classname</p><!--kg-card-begin: markdown--><pre><code class="language-javascript">import React, { Component } from 'react'

export class FileName extends Component {
  render() {
    return &lt;div&gt;$2&lt;/div&gt;
  }
}

export default $1
</code></pre>
<!--kg-card-end: markdown--><p></p><p><code>rpce</code> will create a Pure Component <em>with</em> <code>PropTypes</code> imported and scaffolded in the class.</p><!--kg-card-begin: markdown--><pre><code class="language-javascript">import React, { PureComponent } from 'react'
import PropTypes from 'prop-types'

export class FileName extends PureComponent {
  static propTypes = {}

  render() {
    return &lt;div&gt;$2&lt;/div&gt;
  }
}

export default FileName
</code></pre>
<!--kg-card-end: markdown--><p></p><p>And last, <code>imd</code> creates the destructuring import syntax of a module...something I reach for a lot.</p><!--kg-card-begin: markdown--><pre><code class="language-javascript">import { destructuredModule } from 'module'
</code></pre>
<!--kg-card-end: markdown--><p></p><p>Like I said, they have a <strong>ton</strong> of methods available, but these three are usually the ones I reach for most often! </p>]]></content:encoded></item><item><title><![CDATA[React.Fragment]]></title><description><![CDATA[Use the React.Fragment component to make code shorter and more succinct, by removing unused HTML elements from the DOM.]]></description><link>https://blog.bencomeau.dev/react-fragment/</link><guid isPermaLink="false">5d0e6df41961373a2fc10321</guid><category><![CDATA[React]]></category><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Ben Comeau]]></dc:creator><pubDate>Sat, 16 Mar 2019 18:33:00 GMT</pubDate><media:content url="https://blog.bencomeau.dev/content/images/2019/06/carbon.png" medium="image"/><content:encoded><![CDATA[<img src="https://blog.bencomeau.dev/content/images/2019/06/carbon.png" alt="React.Fragment"><p>You've probably experienced it before: you want to return multiple elements in a <code>render()</code> method so you're forced to wrap them in a <code>&lt;span&gt;</code> or <code>&lt;div&gt;</code> element which will go unused. In comes the <code>React.Fragment</code> component to solve this issue – let's take a quick look at some examples!</p><h3 id="before">Before</h3><p>Using this syntax...</p><!--kg-card-begin: markdown--><pre><code class="language-javascript">render() {
  return (
    &lt;div&gt;
      &lt;h1&gt;Todo Title&lt;/h1&gt;
      &lt;p&gt;Feed the baby&lt;/p&gt;
    &lt;/div&gt;
  )
}
</code></pre>
<!--kg-card-end: markdown--><p></p><p>Will result in the <code>div</code> being added to our dom...</p><!--kg-card-begin: image--><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://blog.bencomeau.dev/content/images/2019/06/Screen-Shot-2019-06-22-at-11.22.38-AM.png" class="kg-image" alt="React.Fragment"><figcaption>Unnecessary div element</figcaption></figure><!--kg-card-end: image--><h3 id="after">After</h3><p>However, using the <a href="https://reactjs.org/docs/react-api.html#reactfragment">React Fragment</a> syntax...</p><!--kg-card-begin: markdown--><pre><code class="language-javascript">render() {
  return (
    &lt;React.Fragment&gt;
      &lt;h1&gt;Todo Title&lt;/h1&gt;
      &lt;p&gt;Feed the baby&lt;/p&gt;
    &lt;/React.Fragment&gt;
  )
}
</code></pre>
<!--kg-card-end: markdown--><p></p><p>Means we have a valid component but without the unused element in the dom...</p><!--kg-card-begin: image--><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://blog.bencomeau.dev/content/images/2019/06/Screen-Shot-2019-06-22-at-11.23.12-AM.png" class="kg-image" alt="React.Fragment"><figcaption>No extra, unused element</figcaption></figure><!--kg-card-end: image--><p>You can see how this would come in handy as your components grow with your application. And starting in <code>v16.2.0</code>, <a href="https://reactjs.org/blog/2017/11/28/react-v16.2.0-fragment-support.html">React took Fragments a step further</a> with shorthand syntax:</p><!--kg-card-begin: markdown--><pre><code class="language-javascript">render() {
  return (
    &lt;&gt; {/* So short, you might even miss it's there! */}
      &lt;h1&gt;Todo Title&lt;/h1&gt;
      &lt;p&gt;Feed the baby&lt;/p&gt;
    &lt;/&gt;
  )
}
</code></pre>
<!--kg-card-end: markdown--><p></p><p>Cheers to less typing and more succinct code!</p>]]></content:encoded></item><item><title><![CDATA[Higher Order Functions]]></title><description><![CDATA[In efforts to reduce redundancy, I've been abstracting certain operations into Higher Order Functions (HOF). A HOF is a function which receives a function as an argument or returns a function.]]></description><link>https://blog.bencomeau.dev/higher-order-functions/</link><guid isPermaLink="false">5c7ea904a38ddd08167a1854</guid><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Ben Comeau]]></dc:creator><pubDate>Tue, 05 Mar 2019 04:24:00 GMT</pubDate><media:content url="https://blog.bencomeau.dev/content/images/2019/03/hof.png" medium="image"/><content:encoded><![CDATA[<img src="https://blog.bencomeau.dev/content/images/2019/03/hof.png" alt="Higher Order Functions"><p>In efforts to reduce redundancy, I've been abstracting certain operations into Higher Order Functions (HOF). A HOF is a function which receives a function as an argument or returns a function. Let's look at a HOF which I often use to handle errors during <a href="https://github.com/axios/axios">Axios</a> requests.</p><p>First, let's define an asynchronous function to get users from a URL: </p><!--kg-card-begin: markdown--><pre><code class="language-javascript">let getUsers = async () =&gt; {
    let users = await axios.get('...')
    
    return users.data
}
</code></pre>
<!--kg-card-end: markdown--><p></p><p>"Wait! What about error handling?!", you say. This is where the HOF comes in. Let's define it:</p><!--kg-card-begin: markdown--><pre><code class="language-javascript">const handleError = fn =&gt; {
    return (...params) =&gt; {
        return fn(...params).catch(err =&gt; console.log(`Error caught!`, err))
    }
}
</code></pre>
<!--kg-card-end: markdown--><p></p><p>As you can see, the HOF takes in a function as an argument, attaches a <code>.catch</code> onto it, then returns the function. Additionally, it unpacks the function's parameters using the spread syntax <code>(...params)</code> so you won't lose any original functionality.</p><p>Great! Now that we've set up everything, let's see it in action:</p><!--kg-card-begin: markdown--><pre><code class="language-javascript">Promise.resolve(handleError(getUsers)())
    .then(result =&gt; console.log(result))
</code></pre>
<!--kg-card-end: markdown--><p></p><blockquote>Notice the placement of the parenthesis! Make sure you don't <em><strong>call</strong></em> <code>getUsers</code> but instead <em><strong>pass</strong></em> it to <code>handleError</code> as an argument, <strong>then</strong> call <code>handleError</code>!</blockquote><p>Boom! We've now got built in error handling which is super reusable and scales well. The possibilities for what you can do with <code>err</code> are endless - it's up to you! Big thanks to Wes Bos for helping me <a href="https://www.youtube.com/watch?v=9YkUCxvaLEk">find the value</a> in this approach.</p>]]></content:encoded></item><item><title><![CDATA[The Power of Async Await]]></title><description><![CDATA[Working with promises has become more comfortable since the introduction of async/await and in my opinion it makes code more readable.]]></description><link>https://blog.bencomeau.dev/async-await/</link><guid isPermaLink="false">5c7f4b9a1961373a2fc0feec</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Node]]></category><dc:creator><![CDATA[Ben Comeau]]></dc:creator><pubDate>Fri, 01 Mar 2019 04:24:00 GMT</pubDate><media:content url="https://blog.bencomeau.dev/content/images/2019/03/asyncAwait.svg" medium="image"/><content:encoded><![CDATA[<img src="https://blog.bencomeau.dev/content/images/2019/03/asyncAwait.svg" alt="The Power of Async Await"><p>Working with promises has become more comfortable since the introduction of async/await and in my opinion it makes code more readable.</p><p>By adding <code>async</code> to a function, it automatically wraps the function in a promise, regardless of its return value. This means <code>async</code> functions will <strong>always return a promise</strong>.</p><!--kg-card-begin: markdown--><pre><code class="language-javascript">const greet = async (name) =&gt; {
  return `Hey, ${name}!`
}

greet('Ben').then(msg =&gt; console.log(msg)) // Hey, Ben!
</code></pre>
<!--kg-card-end: markdown--><p></p><p>Now <code>greet</code> above doesn't really need to run asynchronously but what if we needed to first <code>fetch</code> the user or perform some long-running task? Enter the <code>await</code> keyword!</p><!--kg-card-begin: markdown--><pre><code class="language-javascript">const greet = async (id) =&gt; {
    let response = await fetch(`user-api/${id}`)
    let user = await response.json()
    
    return `Hey, ${user.name}!`
}

greet(7).then(msg =&gt; console.log(msg)) // Hey, Ben!
</code></pre>
<!--kg-card-end: markdown--><p></p><p>By introducing the <code>await</code> keyword, the code pauses until the promise settles and its value becomes available. No more nesting <code>.then</code> methods off the <code>fetch</code> which makes it arguably easier to follow! It should be noted that one cannot use the <code>await</code> keyword <em>outside</em> of an <code>async</code> function – it is a reserved keyword and will result in a syntax error.</p><h3 id="before-and-after">Before and After</h3><p>To help cement the concept that async/await is more readable than chaining <code>.then</code> methods, let's do a little comparison:</p><h4 id="before">Before</h4><!--kg-card-begin: markdown--><pre><code class="language-javascript">const greet = (id) =&gt; {
    return fetch(`user-api/${id}`)
                .then(response =&gt; {
                    return response.json()
                })
                .then(user =&gt; {
                    return `Hey, ${user.name}!`
                })
}

console.log(greet(7)) // Hey, Ben!
</code></pre>
<!--kg-card-end: markdown--><h4 id="after">After</h4><!--kg-card-begin: markdown--><pre><code class="language-javascript">const greet = async (id) =&gt; {
    let response = await fetch(`user-api/${id}`)
    let user = await response.json()
    
    return `Hey, ${user.name}!`
}

greet(7).then(msg =&gt; console.log(msg)) // Hey, Ben!
</code></pre>
<!--kg-card-end: markdown--><p></p><p>Not only does it reduce the code by 3 fewer lines, it also remove complexity – imagine the scenario when you need to make asynchronous calls <em>within</em> one of the <code>.then</code> callbacks! It just gets to be a nested-callback hell. I consider async/await to be a huge improvement to readability and its a practice that I use quite often.</p>]]></content:encoded></item><item><title><![CDATA[Destructuring Assignment]]></title><description><![CDATA[This syntax makes it possible for one to unpack values/properties from arrays/objects and assign them to distinct variables. Let's look at why it's such a handy expression!]]></description><link>https://blog.bencomeau.dev/destructuring-assignment/</link><guid isPermaLink="false">5c7fec3b1961373a2fc0ffe9</guid><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Ben Comeau]]></dc:creator><pubDate>Sat, 23 Feb 2019 03:49:00 GMT</pubDate><media:content url="https://blog.bencomeau.dev/content/images/2019/03/destructuringAssignment.svg" medium="image"/><content:encoded><![CDATA[<img src="https://blog.bencomeau.dev/content/images/2019/03/destructuringAssignment.svg" alt="Destructuring Assignment"><p>The other day I reached for destructuring assignment when I wanted to grab just a single property from an HTTP response. This syntax makes it possible for one to unpack values/properties from arrays/objects and assign them to distinct variables. Let's look at why it's such a handy expression!</p><p>To keep it simple, we'll use the following object in all the examples:</p><!--kg-card-begin: markdown--><pre><code class="language-javascript">const response = {
    status: 200,
    data: [
        {id: 1, name: 'Ben Comeau'},
        {id: 2, name: 'Jane Doe'}
    ],
    path: 'query-endpoint',
    total: 125,
    pages: {
        next: 4,
        previous: 2
    }
}
</code></pre>
<!--kg-card-end: markdown--><p></p><h3 id="single-values">Single values</h3><p>First, let's say you wanted to grab just the <code>status</code> off the <code>response</code> object. Typically one would approach it like this:</p><!--kg-card-begin: markdown--><pre><code class="language-javascript">let status = response.status
</code></pre>
<!--kg-card-end: markdown--><p></p><p>Alternatively, using the destructuring assignment syntax, we can grab it like this:</p><!--kg-card-begin: markdown--><pre><code class="language-javascript">let { status } = response
</code></pre>
<!--kg-card-end: markdown--><p></p><h3 id="multiple-values">Multiple values</h3><p>You may be wondering, "Why? Why not just use the first option?" And I think for this example you'd be right in questioning it. But what about when you'd like to grab <code>data</code> and <code>total</code>, too? We know it would usually look like this:</p><!--kg-card-begin: markdown--><pre><code class="language-javascript">let status = response.status
let data = response.data
let total = response.total
</code></pre>
<!--kg-card-end: markdown--><p></p><p>Now let's see how we'd do this using destructuring assignment syntax:</p><!--kg-card-begin: markdown--><pre><code class="language-javascript">let { status, data, total } = response
</code></pre>
<!--kg-card-end: markdown--><p></p><p>Awesome! Much cleaner and to me, more readable once you're familiar with the syntax. And this is just the tip of the iceberg, really. Let's check out two more cases which I often use.</p><h3 id="nested-properties">Nested properties</h3><p>Notice that the <code>pages</code> property is an object – let's use our new syntax to grab one of its values:</p><!--kg-card-begin: markdown--><pre><code class="language-javascript">let { pages: { next } } = response // 4
</code></pre>
<!--kg-card-end: markdown--><p></p><p>This assigns the <code>response.pages.next</code> value to <code>next</code> – pretty handy! But what if you're trying to use this to assign the value to an existing variable? Or a class property?</p><h3 id="assignment-without-declaration">Assignment without declaration</h3><p>Let's grab that same <code>response.pages.next</code> value but instead assign it to an imaginary class' <code>next</code> property:</p><!--kg-card-begin: markdown--><pre><code class="language-javascript">({
    pages: {
        next: this.next // Notice to where we're assigning the value!
    }
} = response )
</code></pre>
<!--kg-card-end: markdown--><p></p><p>Slightly different syntax as before, but the concept remains the same. Super helpful when dealing with existing objects or class instances.</p><p>I highly recommend reading the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment">MDN docs</a> for more examples of this great feature!</p>]]></content:encoded></item><item><title><![CDATA[Spread Syntax]]></title><description><![CDATA[I love when "new" (is ES6 still considered new?!) syntax comes along which improves readability and makes code more succinct -- the Spread syntax does just that!]]></description><link>https://blog.bencomeau.dev/spread-syntax/</link><guid isPermaLink="false">5c8038831961373a2fc100e8</guid><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Ben Comeau]]></dc:creator><pubDate>Sat, 09 Feb 2019 21:01:00 GMT</pubDate><media:content url="https://blog.bencomeau.dev/content/images/2019/03/spreadSyntax.svg" medium="image"/><content:encoded><![CDATA[<img src="https://blog.bencomeau.dev/content/images/2019/03/spreadSyntax.svg" alt="Spread Syntax"><p>I love when new syntax comes along which improves readability and makes code more succinct. Now I know the spread syntax isn't new to JavaScript (released with ES6) but I do feel it is underutilized. Let's take a look at a few of my common uses for this syntax.</p><h3 id="better-array-literals">Better array literals</h3><p>Quite often I reach for the spread syntax when dealing with arrays, especially when merging two existing arrays.</p><!--kg-card-begin: markdown--><pre><code class="language-javascript">let garnishes = ['orange peel', 'Luxardo cherry']

let oldFashionedIngredients = [
    'rye', 'bitters', 'sugar cube', 'club soda', ...garnishes, 'ice'
]
</code></pre>
<!--kg-card-end: markdown--><p></p><p>This allows us to drop the <code>concat</code> method or <code>slice</code> as the above example would need.</p><h3 id="creating-objects">Creating objects</h3><p>I probably use the spread syntax the most when dealing with objects. Mostly when creating or cloning objects (ES2018+), but also merging objects.</p><!--kg-card-begin: markdown--><pre><code class="language-javascript">let user = {
  firstName: 'Benjamin',
  lastName: 'Comeau'
}

let preferences = {
  firstName: 'Ben',
  email: true,
}

let userAndPreferences = { ...user, ...preferences }
</code></pre>
<!--kg-card-end: markdown--><p></p><p>The somewhat tricky part above is that the object on the right overrides any duplicate property values on the first object. So <code>firstName</code> will actually be <strong>Ben</strong> in this case.</p><h3 id="function-parameters">Function parameters</h3><p>Another place I use it often is when dealing with function parameters. It easily allows one to pass an unknown amount of parameters to a function without needing to reach for <code>.apply</code>, which cleans it up a bit.</p><!--kg-card-begin: markdown--><pre><code class="language-javascript">let summation = (...values) =&gt; values.reduce((a, b) =&gt; a + b)

summation(1,2,3) // 6
summation(1,2,3,4,5) // 15
</code></pre>
<!--kg-card-end: markdown--><p></p><p>Hopefully you see how the spread syntax allows for more succinct code – it's syntax that I often use and enjoy seeing!</p>]]></content:encoded></item><item><title><![CDATA[Babel Configuration]]></title><description><![CDATA[I use Babel, a JavaScript compiler, in order to write bleeding-edge JavaScript which runs well on a variety of targets. I have a go-to setup for Node which has a few neat features that makes code easier to read and maintain.]]></description><link>https://blog.bencomeau.dev/babel-configuration/</link><guid isPermaLink="false">5c816b281961373a2fc101f4</guid><category><![CDATA[Node]]></category><category><![CDATA[Tooling]]></category><dc:creator><![CDATA[Ben Comeau]]></dc:creator><pubDate>Sat, 02 Feb 2019 05:08:00 GMT</pubDate><media:content url="https://blog.bencomeau.dev/content/images/2019/03/babel.svg" medium="image"/><content:encoded><![CDATA[<img src="https://blog.bencomeau.dev/content/images/2019/03/babel.svg" alt="Babel Configuration"><p>I use <a href="https://babeljs.io/">Babel</a>, a JavaScript compiler, in order to write bleeding-edge JavaScript which runs well on a variety of targets. I have a go-to setup for Node which has a few neat features that makes code easier to read and maintain.</p><h3 id="core-setup">Core Setup</h3><p>To start, I pull in the following under <code>devDependencies</code> in my <code>package.json</code> file:</p><!--kg-card-begin: markdown--><pre><code class="language-json">&quot;devDependencies&quot;: {
    &quot;@babel/cli&quot;: &quot;^7.2.3&quot;, // Make sure to pull the latest stable release
    &quot;@babel/core&quot;: &quot;^7.2.2&quot;, // which at the time of writing was v7.
    &quot;@babel/node&quot;: &quot;^7.2.2&quot;,
    &quot;@babel/preset-env&quot;: &quot;^7.3.1&quot;,
    ...
}
</code></pre>
<!--kg-card-end: markdown--><p></p><h3 id="plugins">Plugins</h3><p>Now that I've gotten the base setup going, I add a couple plugins which enable features with which I really like to work:</p><h4 id="class-properties">Class Properties</h4><p>Adding the <code>@babel/plugin-proposal-class-properties</code> plugin allows me to use static class properties – syntax that I often reach for:</p><!--kg-card-begin: markdown--><p>Adding this:</p>
<pre><code class="language-json">&quot;devDependencies&quot;: {
    ...
    &quot;@babel/plugin-proposal-class-properties&quot;: &quot;^7.3.0&quot;,
}
</code></pre>
<p>Allows us to use:</p>
<pre><code class="language-javascript">export class Example {
  static getArray () {
    return [1, 2, 3]
  }
}
</code></pre>
<!--kg-card-end: markdown--><p></p><h4 id="module-resolver">Module Resolver</h4><p>Another plugin near-and-dear to my heart is the <code>babel-plugin-module-resolver</code> which allows me to alias directories for my modules – gets me out of the <code>../../../dot-hell</code> mess!</p><!--kg-card-begin: markdown--><p>Adding this:</p>
<pre><code class="language-json">&quot;devDependencies&quot;: {
    ...
    &quot;babel-plugin-module-resolver&quot;: &quot;^3.1.3&quot;,
}
</code></pre>
<p>Allows us to use:</p>
<pre><code class="language-javascript">// We look at how to set up the &quot;@&quot; alias in the Configuration section below
import { Example } from '@/models/Example'
</code></pre>
<!--kg-card-end: markdown--><p></p><h3 id="configuration">Configuration</h3><p>Great! Now that we're all set up, we need to configure Babel. I chose to use a <code>babel.config.js</code> configuration file as opposed to <code>.babelrc</code> since it allows for comments, programmatic creation, and keeps it more succinct. For the above setup, I would use the following configuration:</p><!--kg-card-begin: markdown--><pre><code class="language-javascript">module.exports = function (api) {
  api.cache(true)

  const presets = ['@babel/preset-env']
  
  const plugins = [
    [require.resolve('@babel/plugin-proposal-class-properties')],
    [require.resolve('babel-plugin-module-resolver'),
      {
        'root': ['./src'], // !! This is where we're setting the &quot;@&quot; alias!
        'alias': {
          '@': './src'
        }
      }
    ]
  ]

  return {
    presets,
    plugins
  }
}

</code></pre>
<!--kg-card-end: markdown--><p></p><p>As you can see, we're configuring the <code>presets</code> and the <code>plugins</code> here – both of which we export – and telling the system to cache the configuration. And notice that we've aliased <code>@</code> to our <code>src</code> directory so just like that, we can avoid the trailing-dot hell.</p><h3 id="running-babel">Running Babel</h3><p>Sweet, we're all set! Last thing I do is to create a few scripts which will actually run our code through Babel during development and before deploying.</p><blockquote>Note: I'm using <a href="https://github.com/remy/nodemon">nodemon</a> for development which is an amazing tool to monitor and reload the Node server automatically after file changes.</blockquote><!--kg-card-begin: markdown--><pre><code class="language-json">&quot;scripts&quot;: {
    &quot;start&quot;: &quot;nodemon --exec babel-node src/index.js&quot;, // Point towards entry file
    &quot;build&quot;: &quot;node_modules/@babel/cli/bin/babel.js src --out-dir dist&quot;,
  }
</code></pre>
<!--kg-card-end: markdown--><p></p><p>That's a wrap! This Babel setup is pretty quick to get running and I find it very helpful when reaching for bleeding-edge JavaScript functionality.</p>]]></content:encoded></item></channel></rss>