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!
Top comments (4)
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.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 globalg
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.
Thanks for your feedback!
Array.prototype.flat: Good point about avoiding Infinity due to circular references. I'll mention using a high-but-not-infinite number instead.
String.prototype.replaceAll: Thanks for the tip! I'll update the article to recommend replaceAll() for better clarity.
performance.now: Noted about timing limitations in different runtimes. I'll add a brief note on that.
Appreciate your insights!
Can you share any specific use cases where these JavaScript tips have notably improved your code efficiency?
Thanks for asking! Here are a couple of ways these tips have improved my code efficiency:
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.
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.
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.