Technology Blog

Look deep into latest news and innovations happening in the Tech industry with our highly informational blog.

The best JavaScript practices to make your code look and work better


We always say that JavaScript is full of surprises. It never fails to amaze us. Every day, we learn something new about this programming language. Something which is very small but can make a huge impact on your code. Something which is worth sharing.

In this article, we’re going to share eight JavaScript hacks that you can use in your day-to-day stuff. So let’s learn something new!

1. Run Event Listeners Only Once

It’s very common to use event listeners in your web app, not just in Vanilla JS applications, but also in modern JS frameworks and libraries like Angular and React.

To cite an example, let’s say we want to do something on a button click. We can use event listeners here. Often, we want to act whenever a specific event fires. But what if we want to do it only once?

Not to worry. We can actually execute our event listeners only once by simply doing this:

const button = document.querySelector('button');

button.addEventListener('click', () => {

    console.log('We will only run once');

},{ once: true })

2. Use the ‘defer’ Attribute

To be honest, all of us have faced a situation where we felt like our web application is getting slower and we are not able to find out why. We’ve felt like we are doing everything as it should be, but still the browser is taking time to show the first content of our application.

Well, this might be because of long scripts getting executed before HTML. Often, we add our scripts in and we forgot that the next statements will not be executed until the script in <HEAD> finishes its execution.

We can simply use the defer attribute with our scripts to execute them after the HTML content.

/* No matter where you place this script tag inside the HTML, this will only run when the HTML content is completely loaded. */

<script src="main.js" defer></script>

3. Fast Conditional Checking

It’s always recommended to use shorthand to make our code look cleaner. As no application can survive without conditionals like the if statement, we should know the shortcuts for that, too. And thankfully, JavaScript provides the && operator.

We can shorten our conditional checking by using the && operator.

let condition = true;
// Long way
if (condition) {
// Short way
condition && someFunction();

4. Random Number in a Given Range

We can simply generate a random number from a given range with just one line of code. These kinds of tricks are very useful in real-world applications.

function randomNumber(num1, num2) {
    return Math.random() * (num2 - num1) + num1;

console.log(randomNumber(50, 100)); // Expected output - random number between 50 and 100 (50 and 100 will be inclusive)

5. Empty an Array in One Line

This is one of the hacks which We love the most. We can empty an array just by giving the value 0 to its length property.

let sampleArray = ["John", "Bob", "Mark", "Alex"];
sampleArray.length = 0;
console.log(sampleArray); // Output - [] (it's empty now)

6. Check Whether the Object Is Empty

We can use the Object.entries() method to check whether an object is empty or not. Since Object.entries() returns the array of the object’s enumerable properties, therefore if the length of that array is 0, that means the object is empty such that the object has 0 property.

let sampleObj = {
    name: "Mark",
    occupation: "Developer"
let emptyObj = {};
console.log(Object.entries(sampleObj).length === 0); // false
console.log(Object.entries(emptyObj).length === 0); // false

7. Filter Duplicate Values From Array

From ES6, we have a new concept in JavaScript which is called Set.

“Set objects are collections of values. You can iterate through the elements of a set in insertion order. A value in the Set may only occur once; it is unique in the Set’s collection.” — MDN Docs

Since Set in JavaScript is a collection of items that are unique, i.e., no element can be repeated, therefore we can use it to filter duplicate values from an array.

This trick is again very simple but very useful. First, we will convert our array into Set, and as Set doesn’t have duplicate values, our new Set will have unique values from our array. Then we simply convert this new Set back into an array.

	let namesArray = ["John", "Bob", "Mark", "Alex", "Mark", "Alain", "Bob"];
	console.log([ Set(namesArray)]); // Output - ["John", "Bob", "Mark", "Alex", "Alain"]

8. Clone Object Using One Line

Since objects in JavaScript are reference types, we can’t simply use = to clone them, so with the below three methods, you can properly clone an object using just one line.

const person = {
    name: "Mark",
    username: "@markcodes"
// Using Object.assign() Method
const clonePerson1 = Object.assign({}, person);
// Using JSON
const clonePerson2 = JSON.parse(JSON.stringify(person));
// Using Spread Operator
const clonePerson3 = { ...person };

For more information and to develop web applications using modern front-end technology, Hire Front-End Developer from us as we give you a high-quality solution by utilizing all the latest tools and advanced technology. E-mail us any clock at – or Skype us: “hkinfosoft“.

To develop your custom web app using JavaScript, please visit our technology page.