Eight Handy JavaScript Tips for Efficient Coding
MD Hasan Patwary
Posted on July 3, 2024
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); // ['π', 'π', 'πΆοΈ', 'π₯']
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
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); // ["π", "π", "π¦"]
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)); // ['π₯°', 'π', 'π', 'π₯²', 'π', 'π']
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("π‘");
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
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
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'}
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`);
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!
Posted on July 3, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.