Better Javascript by using declarative paradigm

3 min read

Image
Learn how to write code that shows your intentions.

As a Javascript Developer, you deal with Arrays all the time. They come from APIs, databases and other sources of data. To make your life easier (and your code better), Javascript creators included many useful methods, to help you to deal with Arrays. Make sure you know how to use them, so your coworkers will love your code.

Transforming Array Content To Some Other Content

Since views usually present different set of properties than their corresponding domain model, you will need to transform this data structure in some elegant way. Instead of writing another for loop identical to those 15 you wrote in your last assignment, it is time to start communicating your intentions instead of focusing on how you implemented it.

To perform replacement of Array elements to another elements, we need to use a map() function, which returns the result as new instance of an Array. In the example below, the users variable holds response from some REST API. To display it in the DOM, you only need given User’s ID and username.

Filtering Out Unwanted Elements From Array

Another situation, when declarative approach makes code cleaner and more readable, is when you need to remove some elements from the Array. For this, we may use a filter() function, which helps us with removing unwanted elements. It iterates through every value in the Array, and if callback function returns false, given element will not be included in the result.

In the example below, user of your application have passed multiple email addresses, and your job is to filter out invalid ones. As usual, focus on declarative approach.

Reducing Array To Single Value

Last, but not least - a reduce() function. It doesn’t only allow to reduce an Array to a single, primitive value, but to another array or object as well. Just like her two sisters mentioned in the previous paragraphs, it also returns a new variable, leaving the original Array intact.

The last example shows how to create an Index from the multiple elements in the Array. It is created to avoid O(n) calls when searching product by its identifier.

Summary

Using one-liners to re-shape an Array is quicker, cleaner and makes code more readable. Please, remember that the code you write, expresses your ideas and way of dealing with a particular problem, not just instructions for the compiler. Everytime programmer see an Imperative solution, there must be some additional time and energy used, to understand what’s going on. Not, when Declarative way is taken, which makes the code easier to grasp.