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
  • Privacy Guides is a non-profit project aimed at providing users with insights into privacy rights, while also recommending best practices or tools to help reclaim privacy in the world of the Internet.

    There are many great articles here, and I will take the example of three concepts that are often confused or misrepresented: Privacy, Security, and Anonymity. While many people who oppose privacy argue that a person does not need privacy if they have 'nothing to hide.' 'This is a dangerous misconception, as it creates the impression that those who demand privacy must be deviant, criminal, or wrongdoers.' - Why Privacy Matters.

    » Read more
  • There is a wonderful place to learn, or if you're stuck in the thought that there's nothing left to learn, then the comments over at Hacker News are just for you.

    Y Combinator - the company behind Hacker News focuses on venture capital investments for startups in Silicon Valley, so it’s no surprise that there are many brilliant minds commenting here. But their casual discussions provide us with keywords that can open up many new insights.

    Don't believe it? Just scroll a bit, click on a post that matches your interests, check out the comments, and don’t forget to grab a cup of coffee next to you ☕️

    » Read more
  • Just got played by my buddy Turso. The server suddenly crashed, and checking the logs revealed a lot of errors:

    Operation was blocked LibsqlError: PROXY_ERROR: error executing a request on the primary

    Suspicious, I went to the Turso admin panel and saw the statistics showing that I had executed over 500 million write commands!? At that moment, I was like, "What the heck? Am I being DDoSed? But there's no way I could have written 500 million."

    Turso offers users free monthly limits of 1 billion read requests and 25 million write requests, yet I had written over 500 million. Does that seem unreasonable to everyone? 😆. But the server was down, and should I really spend money to get it back online? Roughly calculating, 500M would cost about $500.

    After that, I went to the Discord channel seeking help, and very quickly someone came in to assist me, and just a few minutes later they informed me that the error was on their side and had restored the service for me. Truly, in the midst of misfortune, there’s good fortune; what I love most about this service is the quick support like this 🙏

    » 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

Me & the desire to "play with words"

Have you tried writing? And then failed or not satisfied? At 2coffee.dev we have had a hard time with writing. Don't be discouraged, because now we have a way to help you. Click to become a member now!

Have you tried writing? And then failed or not satisfied? At 2coffee.dev we have had a hard time with writing. Don't be discouraged, because now we have a way to help you. Click to become a member 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...