10 JavaScript Tricks That Made Me a Better Developer Overnight
โก Quick Answer
10 JavaScript tips and tricks that advanced developers use daily โ from destructuring shortcuts to optional chaining, these JS pro tips will level up your code.
Get more content like this on Telegram!
Daily AI tips, notes & resources โ free
Advertisement
10 JavaScript Tricks That Made Me a Better Developer Overnight
These ten JavaScript patterns โ optional chaining, nullish coalescing, destructuring, array methods, and more โ are what separate dense, production-grade code from beginner code doing the same job in three times the lines.
I first noticed the gap reading a senior developer's pull request: same JavaScript, but denser, clearer, and dramatically shorter than mine. After Googling each unfamiliar pattern, I found about a dozen techniques I didn't know โ and they were in every piece of code I admired.
None of these are obscure hacks. They're patterns professional developers use every day, and once you know them, you'll reach for them constantly.
Trick 1: Destructuring That Actually Saves Time
Most developers know basic destructuring. Few use all of it.
const user = { name: 'Alice', age: 30, city: 'Berlin', role: 'admin' };
// Basic destructuring
const { name, age } = user;
// Renaming while destructuring
const { name: userName, age: userAge } = user;
// Default values
const { name, theme = 'dark' } = user; // theme is 'dark' if not present
// Nested destructuring
const { address: { city, country = 'Unknown' } } = user;
// Array destructuring (and ignoring elements)
const [first, , third] = [10, 20, 30]; // Skip 20
// Function parameter destructuring (use this everywhere)
function displayUser({ name, role = 'user' }) {
console.log(`${name} (${role})`);
}The last one โ destructuring in function parameters โ changed how I write functions. You get named arguments without the boilerplate of const name = options.name.
Trick 2: Optional Chaining for Safe Navigation
const data = {
user: {
profile: {
avatar: 'https://...'
}
}
};
// Old way โ verbose and fragile
const avatar = data && data.user && data.user.profile && data.user.profile.avatar;
// Modern way
const avatar = data?.user?.profile?.avatar;
// Also works with method calls
const length = data?.user?.getName?.();
// And array access
const firstScore = data?.user?.scores?.[0];This pattern is particularly powerful when working with API responses where fields might be missing.
Trick 3: Nullish Coalescing โ Not the Same as OR
const settings = { timeout: 0, retries: null, label: '' };
// Problem: || treats 0 and '' as falsy
const timeout = settings.timeout || 30; // 30 โ WRONG! 0 is a valid value
const label = settings.label || 'Default'; // 'Default' โ WRONG! '' might be intentional
// Fix: ?? only treats null and undefined as nullish
const timeout2 = settings.timeout ?? 30; // 0 โ correct!
const label2 = settings.label ?? 'Default'; // '' โ correct!I switched a bug-prone form validation function to ?? and eliminated three edge cases in one commit. If you're handling configuration or user settings, use ?? instead of || whenever 0 or empty string are valid values.
Trick 4: Short-Circuit for Conditional Values
const isAdmin = true;
const userRole = 'admin';
// Instead of ternary for truthy rendering
const menu = isAdmin && <AdminMenu />; // undefined if false, <AdminMenu /> if true
// Ternary when you need both branches
const greeting = isAdmin ? 'Hello, Admin' : 'Hello, User';
// Default assignment
let config = null;
config = config || { theme: 'dark', lang: 'en' }; // Only assigns if config is falsy
// Chained nullish assignment
config.theme ??= 'dark'; // Only sets if config.theme is null/undefinedTrick 5: Array Methods That Replace Loops
const products = [
{ id: 1, name: 'Laptop', price: 999, inStock: true },
{ id: 2, name: 'Mouse', price: 29, inStock: true },
{ id: 3, name: 'Keyboard', price: 79, inStock: false },
];
// Find a specific item
const laptop = products.find(p => p.name === 'Laptop');
// Check existence
const hasOutOfStock = products.some(p => !p.inStock);
const allInStock = products.every(p => p.inStock);
// Transform to a different shape
const names = products.map(p => p.name);
// Filter + map in one (flatMap)
const inStockPrices = products.flatMap(p => p.inStock ? [p.price] : []);
// Sum all prices
const total = products.reduce((sum, p) => sum + p.price, 0);
// Group by a property (ES2024)
const grouped = Object.groupBy(products, p => p.inStock ? 'inStock' : 'outOfStock');The Object.groupBy at the bottom is an ES2024 addition that replaces a common reduce pattern. If you find yourself writing the same "group by category" reduce logic, this is the modern replacement.
Trick 6: Object Spreading and Rest
const defaults = { theme: 'dark', lang: 'en', fontSize: 14 };
const userPrefs = { theme: 'light', fontSize: 16 };
// Merge objects โ later values win
const config = { ...defaults, ...userPrefs };
// { theme: 'light', lang: 'en', fontSize: 16 }
// Clone an object (shallow copy)
const cloned = { ...original };
// Add or override properties
const updated = { ...user, lastLogin: Date.now() };
// Remove a property
const { password, ...safeUser } = user; // safeUser has everything except password
// Function rest parameters
function logAll(first, ...rest) {
console.log(first);
rest.forEach(item => console.log(item));
}The { password, ...safeUser } pattern is something I use constantly when sending user data to frontends. Destructure out the sensitive fields, spread the rest.
Trick 7: Dynamic Object Keys
const field = 'username';
const value = 'alice';
// Computed property names
const obj = {
[field]: value, // { username: 'alice' }
[`prev_${field}`]: '', // { prev_username: '' }
};
// Build filter queries dynamically
function buildQuery(filters) {
return Object.entries(filters)
.filter(([, value]) => value !== undefined)
.reduce((query, [key, value]) => ({
...query,
[key]: value
}), {});
}
const query = buildQuery({ name: 'Alice', age: undefined, role: 'admin' });
// { name: 'Alice', role: 'admin' }Trick 8: Tagged Template Literals
// Regular template literals
const greeting = `Hello, ${name}!`;
// Tagged template literals โ the tag function processes the template
function highlight(strings, ...values) {
return strings.reduce((result, str, i) => {
const value = values[i - 1];
return result + (value ? `<mark>${value}</mark>` : '') + str;
});
}
const name = 'Alice';
const output = highlight`Hello, ${name}! Welcome back.`;
// 'Hello, <mark>Alice</mark>! Welcome back.'The styled-components library uses this extensively. Understanding tagged template literals demystifies how CSS-in-JS works.
Trick 9: Async/Await Patterns That Actually Work
// Run promises in parallel (not sequentially)
async function fetchAll() {
// WRONG โ sequential, takes sum of all request times
const users = await fetchUsers();
const products = await fetchProducts();
// RIGHT โ parallel, takes max of all request times
const [users, products] = await Promise.all([fetchUsers(), fetchProducts()]);
}
// Handle errors per-request without try/catch everywhere
async function safeFetch(url) {
try {
const response = await fetch(url);
const data = await response.json();
return { data, error: null };
} catch (error) {
return { data: null, error: error.message };
}
}
const { data, error } = await safeFetch('/api/users');
if (error) console.error(error);The Promise.all pattern is one I see missing from junior code constantly. Three sequential awaits in an async function can be 3ร slower than necessary.
Trick 10: Proxy for Validation and Observation
const handler = {
set(target, key, value) {
if (key === 'age' && (typeof value !== 'number' || value < 0)) {
throw new Error('Age must be a non-negative number');
}
target[key] = value;
return true;
},
get(target, key) {
console.log(`Property ${key} accessed`);
return target[key];
}
};
const user = new Proxy({}, handler);
user.age = 25; // Works
user.age = -1; // Throws: Age must be a non-negative numberProxy is used in Vue.js for its reactivity system and in many validation libraries. Understanding it helps you understand how modern frameworks work under the hood.
Putting It Together
These ten tricks are fundamental JavaScript patterns that experienced developers have internalized, not shortcuts to memorize in isolation. Used naturally, they produce code that's cleaner, shorter, and has fewer bugs โ but they don't substitute for understanding what the underlying values actually are.
Start with optional chaining and nullish coalescing since they have the highest immediate impact on bug count. Then add destructuring defaults to your function signatures. The rest follow naturally as you hit situations where they fit.
For the async patterns mentioned here in a deeper context, our JavaScript async/await guide covers Promises comprehensively. To see these patterns applied in React components, our React hooks tutorial uses modern JavaScript throughout. And for the interview context where these tricks matter most, our JavaScript interview questions guide shows how to explain them to hiring managers.
Further Reading
- State Management in React 2025: Redux vs Zustand vs Jotai
- JavaScript & React Complete Guide 2026 โ From Basics to Pro
- The JavaScript Roadmap for 2025: What to Learn and in What Order
- The React Performance Guide: Making Your App Blazing Fast
- Tailwind CSS vs Bootstrap in 2025: The Final Verdict
- Git for Beginners: Stop Fearing Version Control, Start Loving It
- Python OOP Complete Guide 2026 โ Object-Oriented Programming Mastery
- Async Python: Why Your Programs Are Slow and How to Fix Them
Advertisement
๐ฌ DiscussionPowered by GitHub Discussions
Frequently Asked Questions
Problem Solver and Cloud Expert
Solves complex infrastructure challenges and architects reliable, scalable cloud deployments for every project. Shamshur Rahman keeps AiTechWorldsโ hosting and cloud infrastructure fast, resilient, and cost-efficient.
Not sure yet? Ask AI about this article
Get an instant, unbiased AI summary of โ10 JavaScript Tricks That Made Me a Better Developer Overnightโ.
Advertisement
Related Articles
How to Deploy a React App to Vercel in 10 Minutes
Deploy a React app to Vercel in 10 minutes: from npm create vite to live URL, custom domain setup, environment variables, and preview deployments.
GraphQL vs REST: Which API Style Should You Learn in 2026?
GraphQL vs REST API compared honestly for 2026: when each makes sense, real code examples, and which API style to learn first as a developer.
JavaScript Promises and Async/Await: Finally Understand Them
JavaScript async await and Promises explained clearly: the event loop, Promise chains, async/await patterns, error handling, and common mistakes to avoid.
How to Pass a JavaScript Interview at Google, Meta, or Amazon
How to pass a JavaScript interview at top tech companies: closures, event loop, promises, DOM questions, system design, and real interview questions answered.