The Talent500 Blog
5 useful JavaScript hacks for developers in 2022 1

5 useful JavaScript hacks for developers in 2022

JavaScript is one of the most popular programming languages for frontend development, if not the most. As technologies evolve, it is essential to be up to date. This article lists some of the useful JavaScript hacks for developers. Read on to widen your knowledge.

Front-end development uses multiple technologies, but JavaScript is at the core of all front-end projects. Websites and apps depend on JavaScript for dynamic content generation and interactivity. The programming language empowers over 98% of the internet, which is why it’s a great addition to your resume.

As JavaScript rapidly evolves, front-end developers must keep track of the new features and libraries. In this article, we list incredible JavaScript hacks that you can use to improve your code.

1. Nullish coalescing operator (??)

Introduced in the ES2020, the ?? operator is called the Nullish coalescing operator. It works the same as the || operator and is used to determine that the value to the operator’s left is null or undefined before returning it to the right.

While the behaviour of the ?? operator is similar to the || operator, but it’s stricter. The || operator takes the right operant in the case of false values such as False or 0. The nullish coalescing operator (??) takes the right value only when the left side is set to null or undefined. Therefore, 0 || 1 will return 1 while 0 ?? 1 results in 0.

Here’s an example:

const response = {

  settings: {

   nullValue: null,

   height: 400,

   animationDuration: 0,

   headerText: ”,

   showSplashScreen: false

  }

};

const undefinedValue = response.settings.undefinedValue ?? ‘some other default’; // result: ‘some other default’

const nullValue = response.settings.nullValue ?? ‘some other default’; // result: ‘some other default’

const headerText = response.settings.headerText ?? ‘Hello, world!’; // result: ”

const animationDuration = response.settings.animationDuration ?? 300; // result: 0

const showSplashScreen = response.settings.showSplashScreen ?? true; // result: false

Apart from Internet Explorer, all modern web and mobile browsers support ?? operator.

2. On-demand loading import modules using dynamic import ()

JavaScript allows loading dependencies using the import statement initialization like this:

import defaultExport from “module-name”;

import * as name from “module-name”;

//…

However, using such static import statements that depend on the type = “module” script tag has several drawbacks, such as:

A statically imported module can slow down the loading or execution of the code

It can take up a lot of system memory

It loads every time even when it is required less frequently

One programming hacks to use here is to load modules on-demand based on conditions. It can be used when the statically imported module is not needed immediately or only when certain conditions are triggered.

You can use the dynamic introduction of import () in JavaScript functions and classes. There are two forms to import modules dynamically:

// Form 1

import(‘/modules/my-module.js’)

 .then((module) => {

 // Do something with the module.

 });

 // Form 2

let module = await import(‘/modules/my-module.js’);

3. Replace substrings faster with String.prototype.replaceAll() 

JavaScript developers often use dynamic functions where they have to replace a string or part of a string. The traditional way is to use the String.prototype.replace() method to replace substrings, but it is not efficient. This method only replaces the first occurrence of the substring and not all.

Another important JavaScript hack is to use the String.prototype.replaceAll() method for replacing substrings. It replaces all the occurrences of a substring in the entire code.

Here is an example of the use of String.prototype.replace() and String.prototype.replaceAll() methods to replace all a with Ahui:

// before

console.log(‘a’.replace(/a/g,’Ahui’)) //a

// After simplification

console.log(‘a’.replaceAll(‘a’,’Ahui’)) //Ahui

4. Use Proxy instead of Object.defineProperty

In JavaScript, Object.defineProperty is the static method used to define a new property directly on an object or modify the existing property and return the object. However, one helpful JavaScript hack is to use Proxy instead of Object.defineProperty.

Here are the benefits of using Proxy instead of Object.defineProperty:

  • While Object.defineProperty can proxy only a particular property of an object, the Proxy can proxy the whole object.
  • Unlike Object.defineProperty, Proxy can listen to the new properties added to an object.
  • Object.defineProperty needs to do all the recursions once when all the properties inside the object are to be recursively proxied. However, a Proxy can only be recursive when called. It is not ideal but much better than Object.defineProperty.
  • A proxy can listen to the changes made to an array, but Object.defineProperty cannot.

Here is an example of how to use Proxy:

function reactive(obj) {

  return new Proxy(obj, {

   get(target, key) {

    // Can do dependency collection

    track(target, key)

    return target[key]

  },

  set(target, key, val) {

    target[key] = val

    // trigger dependency

    trigger(target, key)

  }

  })

}

The proxy method acts as a constructor that takes two arguments to generate an object from scratch – a target and a handler.

5. Convert an if/else into a one-line 

The most common practice of using an if-else statement in JavaScript is like this:

if (1 < 2) {

console.log(“True.”);

} else {

console.log(“False”);

}

But there is a powerful programming hack to achieve the same result using a ternary operator and to simplify the code.

Here’s the same code using a ternary operator:

1 < 2 ? console.log(“True.”) : console.log(“False.”);

The ‘:’ is the syntax for the ternary operator and is written like this:

condition ? exprIfTrue : exprIfFalse

Conclusion

We hope these five JavaScript hacks will help you be more productive. They can help you make your JavaScript code much more concise and cleaner. Here are some more JavaScript resources from our blog.

Talent500 is where talent meets opportunity. Join us today to find career-redefining job opportunities with global companies.

 

0
Manik Sharma

Manik Sharma

Manik Sharma specializes primarily in UI or Software Development using Javascript libraries like React and Redux along with HTML, CSS, and other libraries like Bootstrap, Node.js, Express.js, MongoDB. He loves to talk business and think of cool startup ideas. Definitely, an entrepreneur in making. He is equally interested in discussing innovative ideas that can make a huge difference in someone's life.

Add comment