DEV Community

Cover image for Eight Handy JavaScript Tips for Efficient Coding
MD Hasan Patwary
MD Hasan Patwary

Posted on

Eight Handy JavaScript Tips for Efficient Coding

In the ever-evolving world of web development, JavaScript remains a cornerstone for building dynamic and interactive applications. Whether you are a seasoned developer or just starting out, refining your coding techniques can significantly enhance your productivity and code quality. Here are eight handy JavaScript tips to help you write cleaner, more efficient code.

1. Remove Falsy Values from Arrays

When working with arrays, you might encounter unwanted falsy values such as false, NaN, 0, undefined, null, and ''. Removing these values can be effortlessly achieved using the filter method with Boolean as the callback function.

let miscellaneous = ['🍎', false, '🍊', NaN, 0, undefined, '🌶️', null, '', '🥭'];
let fruits = miscellaneous.filter(Boolean);
console.log(fruits); // ['🍎', '🍊', '🌶️', '🥭']
Enter fullscreen mode Exit fullscreen mode

2. Convert Any Value to Boolean

Converting values to their boolean equivalents is a common task. This can be quickly done using the double negation (!!) operator or the Boolean function.

console.log(!!"Jhon"); // true
console.log(!!1); // true
console.log(!!0); // false
console.log(!!undefined); // false
console.log(Boolean("Jhon")); // true
Enter fullscreen mode Exit fullscreen mode

3. Resize Arrays Easily

Adjusting the length of an array is straightforward with the length property. This can be useful when you need to trim an array to a specific size.

let animals = ["🐕", "🐒", "🦊", "🐅"];
animals.length = 3;
console.log(animals); // ["🐕", "🐒", "🦊"]
Enter fullscreen mode Exit fullscreen mode

4. Flatten Multi-dimensional Arrays

Handling multi-dimensional arrays can be simplified with the flat method, which flattens nested arrays into a single-level array. For deeply nested arrays, use a specific depth or a high-but-not-infinite number as the parameter to avoid potential issues with circular references.

let smileys = ['🥰', ['😄', '😃'], '😉', ['🥲', '😑']];
console.log(smileys.flat()); // ['🥰', '😄', '😃', '😉', '🥲', '😑']

let smileys2 = ['🥰', ['😄', '😃', ['🥲', '😑']], '😉'];
console.log(smileys2.flat(100)); // ['🥰', '😄', '😃', '🥲', '😑', '😉']
Enter fullscreen mode Exit fullscreen mode

5. Short Conditionals

JavaScript allows for concise conditional statements using logical operators. This can make your code more readable and succinct.

const captain = "Jhon";

// Instead of this
if (captain === "Jhon") {
    console.log("❤️");
}

// Use this
captain === "Jhon" && console.log("❤️");

// And instead of this
if (captain !== "Jhon") {
    console.log("😡");
}

// Use this
captain === "Jhon" || console.log("😡");
Enter fullscreen mode Exit fullscreen mode

6. Replace All Occurrences of a String

Replacing all instances of a substring in a string can be done using a regular expression with the replace method.

const quote = "React is a JS framework & this framework is the most popular front-end framework right now";
console.log(quote.replace(/framework/g, "library"));
// React is a JS library & this library is the most popular front-end library right now
Enter fullscreen mode Exit fullscreen mode

Replacing all instances of a substring in a string can now be done using the replaceAll method introduced in ES2021, which is supported by all major browsers.

const quote = "React is a JS framework & this framework is the most popular front-end framework right now";
console.log(quote.replaceAll("framework", "library"));
// React is a JS library & this library is the most popular front-end library right now
Enter fullscreen mode Exit fullscreen mode

7. Log Values with Variable Names

When debugging, logging variable names along with their values can be immensely helpful. JavaScript's object shorthand notation makes this easy.

const library1 = "jQuery";
const library2 = "React";

console.log({ library1 }); // {library1: 'jQuery'}
console.log({ library2 }); // {library2: 'React'}
Enter fullscreen mode Exit fullscreen mode

8. Measure Performance of a Task

Understanding the performance of your code is crucial for optimization. The performance.now method provides high-resolution timestamps to measure execution time. Be aware of timing limitations in different runtimes.

const startTime = performance.now();

for (let i = 0; i <= 50; i++) {
    console.log(i);
}

const endTime = performance.now();
console.log(`Loop took ${endTime - startTime} milliseconds to finish`);
Enter fullscreen mode Exit fullscreen mode

By incorporating these tips into your JavaScript practices, you can write more efficient and readable code, streamline your debugging process, and enhance overall performance. Happy coding!

Top comments (4)

Collapse
 
oculus42 profile image
Samuel Rouse

Thanks for putting this list together! A couple of notes:

Array.prototype.flat

For flattening arrays avoid using Infinity, as any circular reference will exceed the maximum call stack.

const a = [1, 2];
const b = [3, a];
a.push(b); // circular reference

a.flat();
// basically returns [ 1, 2, 3, a]

a.flat(Infinity);
// RangeError: Maximum call stack size exceeded
Enter fullscreen mode Exit fullscreen mode

For most purposes you should know the expected depth of data, or be able to set a high-but-not-infinite number, like .flat(100).

String.prototype.replaceAll

ES2021 introduced replaceAll to resolve the decades-long confusion about .replace() requiring a regular expression with the global g flag to replace all. Since late 2020 the major browsers have supported .replaceAll() and I recommend using it in place of regex for developer sanity. 😀

performance.now

This is something I use all the time, but it can be important to be aware of the timing limitations that exist in different runtimes, especially since 2018.

Collapse
 
mdhassanpatwary profile image
MD Hasan Patwary

Thanks for your feedback!

  1. Array.prototype.flat: Good point about avoiding Infinity due to circular references. I'll mention using a high-but-not-infinite number instead.

  2. String.prototype.replaceAll: Thanks for the tip! I'll update the article to recommend replaceAll() for better clarity.

  3. performance.now: Noted about timing limitations in different runtimes. I'll add a brief note on that.

Appreciate your insights!

Collapse
 
polterguy profile image
Thomas Hansen

Can you share any specific use cases where these JavaScript tips have notably improved your code efficiency?

Collapse
 
mdhassanpatwary profile image
MD Hasan Patwary

Thanks for asking! Here are a couple of ways these tips have improved my code efficiency:

  1. Removing Falsy Values from Arrays: In a dashboard project, I used .filter(Boolean) to clean up API data before rendering it on charts, which made the data more reliable and the process more efficient.

  2. Replacing All Occurrences of a String: For localizing a web application, replaceAll simplified the process of updating placeholder text across different languages without regex errors.

  3. Measuring Performance: I used performance.now to optimize a sorting algorithm in a data processing app, allowing me to compare different methods and choose the most efficient one.

These tips have been invaluable in writing cleaner and more efficient code.