9 Most Useful JavaScript Tips and Tricks

9 Most Useful JavaScript Tips and Tricks

In this article I will share with you some really handy JavaScript tips.

Let’s get started!

1. Run the event listener only once.

If you want to add an event listener but have it run only once, you can use the once option:

javascript
element.addEventListener('click', () => console.log('I run only once'), {
    once: true
});           

2. console.log variable wrapping

You can wrap your console.log() arguments with curly brackets to see their names. It’s a shorthand for logging objects:

Variable Wrapping

3. Remove duplicate elements from an array:

javascript
const numbers = [2, 3, 4, 4, 2];

console.log([...new Set(numbers)]); // [2, 3, 4]

4. Remove all falsy values from an array:

javascript
const myArray = [1, undefined, NaN, 2, null, '@denicmarko', true, 3, false];

console.log(myArray.filter(Boolean)); // [1, 2, "@denicmarko", true, 3] 

5. Short-circuit conditionals

If you have to execute a function only if the condition is true, you can use short-circuit.

javascript
//If you have to execute a function only if the condition is true:
if (condition) {
    doSomething();
}

// You can use short-circuit:
condition && doSomething();           

6. DRY

Don’t repeat yourself.

javascript
const myTech = 'JavaScript';
const techs = ['HTML', 'CSS', 'JavaScript'];

// Instead of:
if (myTech === 'HTML' || myTech === 'CSS' || myTech === 'JavaScript') {
	// do something
}

// You can:
if (techs.includes(myTech)) {
 	// do something 
}   

7. Get the min/max value from an array

You can use Math.min() or Math.max() combined with the spread operator to find the minimum or maximum value in an array.

javascript
const numbers = [6, 8, 1, 3, 9];

console.log(Math.max(...numbers)); // 9
console.log(Math.min(...numbers)); // 1           

8. Sum an array

You can use the reduce method to calculate the sum of all elements in an array:

javascript
const myArray = [10, 20, 30, 40];
const reducer = (total, currentValue) => total + currentValue;

console.log(myArray.reduce(reducer)); // 100           

9. Copy to clipboard

You can use the Clipboard API to create the “Copy-to-clipboard” functionality, but note that it only works in secure contexts (HTTPS):

javascript
function copyToClipboard(text) {
  return navigator.clipboard.writeText(text)
    .then(() => {
      console.log('Text copied to clipboard!');
    })
    .catch(err => {
      console.error('Failed to copy text: ', err);
    });
}

Which JavaScript tip is your favorite? Let me know!