5 Essential Tips and Tricks for Writing Clean JavaScript Code

4 min read
May 19, 2024
(Source geeks for geeks)

JavaScript offers a multitude of features, with new sets being added annually. This constant evolution is a great reason for us to continually enhance our programming skills. By diving into and utilizing these JavaScript tips and tricks, we can write code that is not only more concise and quicker but also easier to understand. Additionally, it helps us stay current in the fast-paced software development landscape.

Every feature highlighted in this article, such as the spread operator, pad, and Intl.DateTimeFormat, was rolled out with ES6 or subsequent versions. These handy shortcuts enable you to compose tidy JavaScript code while also optimizing it.

1. Groupping array of objects by property

A common challenge developers face is transforming an array of objects into a new array organized by a specific property. This technique is particularly useful for combining two arrays. If you look up each item by its id sequentially, the process has an asymptotic complexity of O(N²). But by converting one of the arrays into a map, you can access its elements in constant O(1) time. This approach lowers the complexity of merging the arrays to O(N) and only uses a small amount of extra memory due to pointers.

function groupArrayOfObjects(array, property) {
return array.reduce((map, fruit) => {
const group = map.get(fruit[property]) || [];
group.push(fruit);
map.set(fruit[property], group);
return map;
}, new Map());
}

2. Flooring the number

The flooring number is relatively simple to understand. That said, you can make longer arithmetic operations more concise and easier to read with a few adjustments.

Math.floor(1.245) == ~~1.245

The ~~ doesn't exactly function as a floor operation; it doesn't round down but rather eliminates the decimal portion of a number. When you compare the results, they turn out to be the same.

3. Formatting date

Dealing with date formatting can be challenging. There are many libraries available to help with this task, such as dateformat. Dateformat is highly popular and widely used. However, it's not the only choice out there. If you prefer to format dates without relying on a library to keep your bundle size smaller, you can choose Intl.DateTimeFormat instead.

Formatting a date is easy, quick, and uncomplicated. It lets you pick from different options and can even show the date in the current language.

function formatDate(date, locale) {
const dateFormat = new Intl.DateTimeFormat(locale, { hour: 'numeric', minute: 'numeric', second: 'numeric' });
return dateFormat.format(date);
}

4. Ensure all numbers in the date are displayed with two digits.

When looking at dates, the number of characters can differ based on the specific date. For example, the length varies between these two dates when formatted as year-month-date:.

1. 1. 2024 => 2024-0-1
10.2. 2024 => 2024-1-10

In situations like these, making the number two digits long can be really useful. (This doesn't refer to months starting from 0 in JavaScript, instead of 1).

function formatDate2Digit(date) {
const pad = num => (num + '').padStart(2, '0');
return [date.getFullYear(), pad(date.getMonth() + 1), pad(date.getDate())].join('-') +
' ' + [pad(date.getHours()), pad(date.getMinutes()), pad(date.getSeconds())].join(':')

}

5. Copying array

Say goodbye to using lodash deep copy or other libraries for duplicating objects. JavaScript has made copying incredibly simple. Ever since the spread operator was introduced, you can now clone objects with just a single line of code.

const array = [1, 2, 3, 4, 5];
console.log(...fruits);

Conclusion

I hope you find some of these tips useful down the road. Personally, they become incredibly valuable when I'm tackling large, intricate applications. They help me save time, shorten my code, reduce the bundle size, and eliminate the necessity for additional libraries. What tips do you find most time-saving?

Read more in Tech