A practical guide to writing more functional JavaScript
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
- Parse the query string.
- Get the
redirect_to
value. - Decode that value.
- 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: