10 JavaScript Tricks Only Advanced Developers Know About
Support Freedium
Dear Freedium users,
We've updated our donation options to provide you with more ways to support our
mission. Your contributions are invaluable in helping us maintain and improve
Freedium, ensuring we can continue to provide unrestricted access to quality
content.
We now offer multiple platforms for donations, including Patreon, Ko-fi, and
Liberapay. Each option allows you to support us in the way that's most convenient for
you.
Your support, no matter the platform or amount, makes a significant difference. It
allows us to cover our operational costs and invest in enhancing Freedium's features
and reliability.
Thank you for being a part of the Freedium community and for your continued
support.
Choose Your Preferred Donation Platform:
< Go to the original
1/6
Preview image
JavaScript, a dynamic and versatile language, offers a treasure trove
of features often overlooked by beginners and intermediate…
JavaScript, a dynamic and versatile language, offers a treasure trove of features often
overlooked by beginners and intermediate developers. Advanced developers, however,
know how to harness these hidden gems to write elegant, efficient, and powerful code. In
this article, we'll uncover 10 JavaScript tricks that can elevate your coding game.
1. Destructuring with Default Values
Destructuring in JavaScript is a popular feature, but advanced developers use it with default
values to make code more robust.
2/6
const user = { name: "Alice" };
const { name, age = 25 } = user;
console.log(name); // Alice
console.log(age); // 25
This trick is particularly useful for handling incomplete data objects without resorting to
verbose null-checks.
2. Dynamic Object Keys
Advanced JavaScript allows you to create object keys dynamically, making your code more
adaptable.
const key = "dynamicKey";
const obj = {
[key]: "value",
};
console.log(obj.dynamicKey); // value
This is particularly handy for creating objects from user input or external data.
3. Optional Chaining (?.) for Deep Object Access
The optional chaining operator (?.) simplifies accessing nested properties without worrying
about undefined errors.
const user = { address: { city: "New York" } };
console.log(user.address?.city); // New York
console.log(user.profile?.age); // undefined
This removes the need for lengthy if checks and makes your code cleaner.
4. Nullish Coalescing (??)
While || is often used for fallback values, it treats 0, false, and '' as falsy. The ?? operator
only checks for null or undefined.
const value = 0;
console.log(value || 10); // 10 (fallback applied)
console.log(value ?? 10); // 0 (fallback not applied)
This subtle distinction can prevent unexpected behavior in logical operations.
5. Short-Circuiting with Logical Operators
Logical operators (&& and ||) are not just for conditions; they can short-circuit operations
effectively.
3/6
const isAuthenticated = true;
isAuthenticated && console.log("User is authenticated");
const fallback = "default";
const data = null || fallback;
console.log(data); // default
These tricks minimize boilerplate code while preserving readability.
6. Memoization with Closures
Memoization is a technique to cache expensive function calls. JavaScript closures make this
elegant.
const memoizedAdd = (() => {
const cache = {};
return (a, b) => {
const key = `${a},${b}`;
if (cache[key]) return cache[key];
const result = a + b;
cache[key] = result;
return result;
};
})();
console.log(memoizedAdd(2, 3)); // 5 (calculated)
console.log(memoizedAdd(2, 3)); // 5 (cached)
This is a practical optimization for repetitive computational tasks.
7. Using Intl for Locale-Sensitive Formatting
The Intl object simplifies tasks like formatting dates, numbers, and currencies globally.
const number = 1234567.89;
const formatted = new Intl.NumberFormat("en-US", {
style: "currency",
currency: "USD",
}).format(number);
console.log(formatted); // $1,234,567.89
Advanced developers use this to ensure applications handle localization gracefully.
8. Debouncing and Throttling for Performance
Debouncing and throttling are vital for optimizing event handling.
Debouncing: Executes a function after a delay, resetting the timer if invoked again during
the delay.
4/6
const debounce = (fn, delay) => {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), delay);
};
};
const onResize = debounce(() => console.log("Resized!"), 300);
window.addEventListener("resize", onResize);
Throttling: Limits the function execution to once per specified interval.
const throttle = (fn, interval) => {
let lastTime = 0;
return (...args) => {
const now = Date.now();
if (now - lastTime >= interval) {
lastTime = now;
fn(...args);
}
};
};
const onScroll = throttle(() => console.log("Scrolling!"), 500);
window.addEventListener("scroll", onScroll);
9. Custom Map Iteration with forEach
Map objects maintain the insertion order of keys and allow for custom iterations.
const map = new Map([
["key1", "value1"],
["key2", "value2"],
]);
map.forEach((value, key) => {
console.log(`${key}: ${value}`);
});
Unlike plain objects, Map supports non-string keys and preserves order, making it ideal for
advanced use cases.
10. Asynchronous Iteration with for await...of
Handling asynchronous data streams is seamless with for await...of.
5/6
async function* fetchData() {
yield await fetch("https://api.example.com/data1").then((res) => res.json());
yield await fetch("https://api.example.com/data2").then((res) => res.json());
}
(async () => {
for await (const data of fetchData()) {
console.log(data);
}
})();
This pattern simplifies working with APIs, streams, and other asynchronous tasks.
Conclusion
Mastering JavaScript requires exploring beyond the basics. The tricks above can help you
write cleaner, more efficient, and professional-grade code. Whether it's optimizing
performance, handling localization, or managing asynchronous operations, these
techniques will set you apart as an advanced developer. Start experimenting today and
elevate your JavaScript skills!
In Plain English 🚀
Thank you for being a part of the In Plain English community! Before you go:
Reporting a Problem
Sometimes we have problems displaying some Medium posts.
If you have a problem that some images aren't loading - try using VPN. Probably you have problem
with access to Medium CDN (or fucking Cloudflare's bot detection algorithms are blocking you).
Auto Filling...
6/6