How To Write Clean Code With These 5 Jav ...

How To Write Clean Code With These 5 Javascript Tips And Tricks?

Feb 05, 2024

Javascript has lots of features. Every year new bunch of them gets implemented. That is why we should always improve our programming knowledge. By exploring and applying these javascript tips and tricks we enable ourselves to create shorter, faster, and simpler code, and stay up to date with the ever-changing world of software development.

All of the features mentioned in this article were introduced in ES6 or later (spread operator, pad, Intl.DateTimeFormat). Thanks to these shortcuts you are able to write clean javascript code, and at the same time do the javascript optimatization.

1. Groupping array of objects by property

Many developers struggle to convert an array of objects into an array grouped by property. This comes especially handy when merging two arrays. When you search for each item connected by id the asymptotic complexity would be O(N²). However, when you convert one of the arrays to a map you can access its items in constant O(1) time. That reduces the complexity of the merger to O(N), and consumes only a bit more memory, thanks to the 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 quite straightforward. However, it can be done shorter with improved readability when making longer arithmetical operations.

Math.floor(1.245) == ~~1.245

The ~~ are not exactly floor, they do not round down, and they remove the decimal part of a number. When compared the result of the operations is the same.

3. Formatting date

Formatting dates can be quite a hassle. Many libraries are doing exactly that for example dateformat. Dateformat is one of the most widely adopted and used. But it is not your only option. When you would like to do it without the library reducing your bundle size you can opt for Intl.DateTimeFormat.

Formatting date is simple, short, and straightforward. Allowing you to choose from various options, and even display the date as supposed 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. Formatting all numbers in date to 2 digits

When comparing dates the length of the date can vary depending on the date. These 2 dates have different lengths, when formatted year-month-date:

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

In those cases padding the number to the length of 2 comes in handy. (Not speaking of the months starting in javascript from 0, rather than 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

Forget copying with the loadash deep copy, or other libraries providing this function. Copying has never been easier in javascript. After introducing the spread operator copying can be done in one line.

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

Conclusion

I hope some of the tips will help you in the future. For me, these come in especially handy when writing big complex applications. Saving my time, reducing the length of code and bundle size, and resolving the need for libraries.
And what are the tips that save you the most time?

Gefällt dir dieser Beitrag?

Kaufe Oren Holiš einen Kaffee