Only One Way Out of a Function

A programming style I try to practice could be described as: “there should be only one way out of a function.” Early returns can often cause more confusion than they’re worth. When possible, I avoid them in favor of a single return. Here’s a demonstration of this style. Common Code: Early Returns Imagine a function that takes as an argument an HTTP response object responding to .ok and returns a message string. Here’s an implementation, with an early return, when response.ok is truthy: ...

May 2, 2022

How to Organize JavaScript Imports

The import statements at the top of a JavaScript component file can be a confusing, duplicative, churning mess. Is there a way to organize them that makes sense and scales? In this post, I’d like to share the way I handle this detail. Who Cares? Wait; who cares? Isn’t this like discussing the color of the bike shed? Years of programming with other humans has taught me that, for loosely-defined tasks like this, any convention is better than no convention. Without it, you’ll see in many, many codebases: ...

August 30, 2021

How I Clean Up JavaScript Dependencies

Unused dependencies are bad: they increase the size of your project, slow down your processes, require upgrades, and send incorrect messages to fellow developers about what’s important. Make your project better by periodically auditing your dependencies, and removing those that are unused. If a dependency is in your bundle and is not being used right now, get rid of it! Legacy codebases are littered with rainy-day libraries. Rip them out and start again. ...

August 3, 2020

JavaScript Equality

A few weeks ago, I built an app with React and create-react-app that I call ‘JavaScript Equality’. View deployment here. This application demonstrates the JavaScript value-comparison operators == and ===. It’s inspired by the JavaScript Equality Table. The image above shows why the threequals is superior to the twoquals equals. If you want true equality, the kind of logic you’d expect with any other programming language, use threequals. My favorite implementation detail of this app is the data model, which is created in the constructor function: ...

July 17, 2018

Build URLs with Window Location

Want to build URLs with JavaScript? Try thewindow.location object. This came from a React.js project we’re working on. It uses ES6 template string interpolation, which isn’t necessary but definitely is nice: `${window.location.protocol}//${window.location.host}/posts/${this.props.postID}/edit` Which becomes: "https://secret-project.com/posts/42/edit"

September 23, 2015