Eight Handy JavaScript Tips for Efficient Coding

mdhassanpatwary

MD Hasan Patwary

Posted on July 3, 2024

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!

πŸ’– πŸ’ͺ πŸ™… 🚩
mdhassanpatwary
MD Hasan Patwary

Posted on July 3, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related