Programming Series with Array and Object Data in Javascript - How to Handle Data Effectively

Programming Series with Array and Object Data in Javascript - How to Handle Data Effectively

Daily short news for you
  • Morning news, does everyone remember the lawsuit of Ryan Dahl - or more accurately, the Deno group against Oracle over the name JavaScript?

    Oracle has responded that they are not giving up the name JavaScript 🫣

    https://x.com/deno_land/status/1876728474666217739

    » Read more
  • Are people taking their Tet holidays early or what? Traffic has dropped significantly this whole week 😳. It's a bit sad to talk to myself, so if anyone passes by and reads this, please drop a "comment" for some fun at home. You can say anything since it's anonymous 😇🔥

    » Read more
  • Someone asked me where I get my news so quickly, or how I find so many tools and projects... where do I get all of that? Well, there’s a source far on the horizon but close right in front of you, and that is the Github Trending page.

    This page tracks the repositories that have the most "stars" according to day/week/month. It also allows you to filter by programming language, and each language represents a kind of theme. For example, Python is buzzing about AI, LLMs..., Rust has all the super powerful tools, and Go is... just a continuous plaything 😁. Meanwhile, JavaScript 🫣😑

    » Read more

Issue

Note: The following article is my personal opinions on data handling. This includes my experiences in real projects. Readers can consider this as a reference or leave comments for further discussion.

In my previous article, I introduced some ways of handling data. Today, I will focus more on how I handle data in Javascript and how to write code that is easier to read for future maintenance.

Writing code to make it work is fast, but writing code to make it easy to maintain requires the writer to have certain experience. In addition, organizing code and flow will take more time. The time it takes to maintain a project is usually much longer than the time it takes to release the product for the first time, not to mention new people joining the project. Therefore, if your code organization is good, you will save a lot of time in the future.

Handling data is a frequent task in project functionalities. This includes actions like filtering, mapping, and transforming data in arrays or objects. The following 4 techniques that I often use contribute to making my code clearer.

Immutability

Immutability means that once a variable is declared, it should never be changed. If you want to modify the data, copy it to another variable. At first, this may seem unreasonable because variables in programming languages are allowed to be changed and reassigned normally. This also improves performance and saves memory compared to creating additional variables.

In Javascript, there is no definition of data type. Declaring a variable with the var or let keyword allows us to easily change its data or even its data type in the future. This creates flexibility, but the hidden consequences seem to be more than that.

In a code block with tens or hundreds of lines of code, changing the data of a variable can sometimes make it difficult to track the value of the variable. You will have to wonder where the value of the variable is changed or what is changed... To solve this problem, try to use const as much as possible. When using const, you cannot reassign a value to that variable anymore.

However, const alone is not enough. In Javascript, non-primitive data types such as Array, Object... have reference nature. The data, when assigned, can still change the values of the elements, properties inside it. So sometimes if you accidentally modify the reference data, other variables can also be changed unintentionally. To understand more, you can read my article A Few Things About Object Reference in Javascript. Forget It And How Annoying It Can Be! on estacks.

Instead of updating the reference data directly, we should make a "deep" copy of the reference-like data to another variable for processing. Avoid changes that cause hidden errors in the future.

Focus on What to Do Instead of How to Do It

To explain this, I will take an example of a function that retrieves the name attribute in an array of data:

const users = [
  {
    name: "A",  
    age: 18
  },  
  {
    name: "B",  
    age: 19
  },  
  {
    name: "C",  
    age: 20
  },  
];

// The first way, write a function using map to retrieve the name
function usersWithName(users) {
  return users.map(function(user) {
    return {
      name: user.name,  
    };
  });
};

// The second way, still use map but apply curry function
const get = (attribute) => (data) => data[attribute];
const usersWithName = users.map(get("name"));

In the above example, I used a Curry function. If you're not familiar with curry functions and their applications, you can read more at What is a Curry Function? A Delicious Curry and How to Enjoy It?.

Returning to the example above, I have two ways to achieve the same result.
The first way is the usual way, I write the code step by step to get the desired result.
The second way, instead of following step-by-step thinking, I create a get function to retrieve the attribute's data in an object, and then pass it to the map function.

By the second way, if we create a habit of defining functions like get, it will help create uniformity throughout the project. In addition, when readers see get, they can understand what the code is doing.

The More Reusable, The Better

Try to create code snippets that focus on a specific function that will make your code reusable. At the same time, it also creates consistency throughout the project, which means that when you see it, you can know what it is doing.

Looking at the above example in the second way, the get function can be reused multiple times. Instead of get("name"), I can have get("age")... Moreover, every time we see the get function, we can immediately know that it "retrieves the value of the attribute" instead of having to read a long code snippet like the first way to understand what the writer wants to do.

Apply Common Data Handling Libraries

The benefits of creating reusable code snippets have been discovered by the community for a long time. They have created libraries consisting of a collection of functions to help us handle data. One of them is underscore, lodash, ramda... They are widely used in projects on Github, with a large number of commits and collaborators.

For example, in lodash, there are nearly 50 utility functions to handle Object data. Among them are functions similar to get in my example, and almost anything you want to do has a function that can meet your needs.

In my example, I will combine the functions in lodash to solve the initial example, and there is an additional condition that the order of name to be retrieved should be sorted in descending order of age:

_.chain(users).orderBy("age", "desc").map("name").value();
Premium
Hello

The secret stack of Blog

As a developer, are you curious about the technology secrets or the technical debts of this blog? All secrets will be revealed in the article below. What are you waiting for, click now!

As a developer, are you curious about the technology secrets or the technical debts of this blog? All secrets will be revealed in the article below. What are you waiting for, click now!

View all

Subscribe to receive new article notifications

or
* The summary newsletter is sent every 1-2 weeks, cancel anytime.

Comments (0)

Leave a comment...
Scroll or click to go to the next page