Member-only story
Imperative vs Declarative JavaScript

I was recently doing a JavaScript code review and came across a chunk of classic imperative code (a big ol’ for loop) and thought, here’s an opportunity to improve the code by making it more declarative. While I was pleased with the result, I wasn’t 100% certain how much (or even if) the code was actually improved. So, I thought I’d take a moment and think through it here.
Imperative and Declarative Styles
To frame the discussion, imperative code is where you explicitly spell out each step of how you want something done, whereas with declarative code you merely say what it is that you want done. In modern JavaScript, that most often boils down to preferring some of the late-model methods of Array and Object over loops with bodies that do a lot of comparison and state-keeping. Even though those newfangled methods may be doing the comparison and state-keeping themselves, it is hidden from view and you are left, generally speaking, with code that declares what it wants rather being imperative about just how to achieve it.
The Imperative Code

Let’s break down the thought process required to figure out what’s going on here.
- JavaScript isn’t typed, so figuring out the return and argument types is the first challenge.
- We can surmise from the name of the function and the two return statements that return literal boolean values that the return type is boolean.
- The function name suggests that the two arguments may be arrays, and the use of needle.length and haystack.indexOf confirms that.
- The loop iterates the needle array and exits the function returning false whenever the currently indexed value of the needle array is not found in the haystack array.
- If the loop completes without exiting the function, then we found no mismatches and true is returned.
- Thus, if all the values of the needle array (in any order) are found in the haystack array, we get a true return, otherwise false.