10 JavaScript Tricks Every Developer Should Know
Short, sharable tricks with copy-paste code. Save this post — share it!
Quick list
- 1. Short-circuit default values
- 2. Destructuring defaults
- 3. Optional chaining & nullish coalescing
- 4. Toggling booleans
- 5. Async IIFE for top-level await
- 6. Grouping logs with console.group
- 7. Debounce helper pattern
- 8. Use Set to dedupe arrays
- 9. Object.fromEntries for transforms
- 10. Short async error handling trick
1) Short-circuit default values
const name = userInput || 'Guest';
// but beware: treats '', 0, false as falsy. Prefer nullish if you want only null/undefined:
const name2 = userInput ?? 'Guest';
2) Destructuring defaults
const { a = 1, b = 2 } = options || {};
3) Optional chaining
const phone = user?.contact?.phone ?? 'N/A';
5) Async IIFE for top-level async
(async () => {
const r = await fetch('/api/data');
const data = await r.json();
console.log(data);
})();
7) Debounce helper
function debounce(fn, wait=300){
let t;
return (...args) => {
clearTimeout(t);
t = setTimeout(()=> fn(...args), wait);
};
}
9) Object transforms with fromEntries
const entries = Object.entries(obj).map(([k,v]) => [k.toUpperCase(), v]);
const newObj = Object.fromEntries(entries);
10) Short async error handling
const to = (p) => p.then(data => [null, data]).catch(err => [err]);
const [err, data] = await to(fetchData());
if(err) return console.error(err);
Comments
Post a Comment