A practical guide to writing more functional JavaScript

Nadeesha Cabral
4 min readJan 14, 2019

Functional programming is great. With the introduction of React, more and more JavaScript front-end code is being written with FP principles in mind. But how do we start using the FP mindset in everyday code we write? I’ll attempt to use an everyday code block and refactor it step by step.

Our problem: A user who comes to our /login page will optionally have a redirect_to query parameter. Like /login?redirect_to=%2Fmy-page. Note that %2Fmy-page is actually /my-page when it’s encoded as the part of the URL. We need to extract this query string, and store it in local storage, so that once the login is done, user can be redirected to the my-page.

Step #0: The imperative approach

If we had to express the solution in the simplest form of issuing a list of commands, how would we write it? We will need to

  1. Parse the query string.
  2. Get the redirect_to value.
  3. Decode that value.
  4. Store the decoded value in localStorage.

And we have to put try catch blocks around “unsafe” functions as well. With all of that, our code block will look like:

--

--

Nadeesha Cabral

Hi, I’m Nadeesha. I work with computers a lot. I write about software development, and a few other things.