10 JavaScript Tricks That Made Me a Better Developer Overnight
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
10 JavaScript Tricks That Made Me a Better Developer Overnight
I remember looking at a senior developer's pull request and thinking it was a different language. Same JavaScript, but somehow denser, clearer, and dramatically shorter than mine.
After three hours of Googling what each unfamiliar pattern was called, I realized there were about a dozen JavaScript techniques I didn't know — and they were in every piece of code I admired.
These aren't obscure hacks. They're patterns that professional developers use every day. Once you know them, you'll use 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/undefined
Trick 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 number
Proxy 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 aren't tricks — they're fundamental JavaScript patterns that experienced developers have internalized. Once you start using them naturally, you'll write code that's cleaner, shorter, and has fewer bugs.
Start with optional chaining and nullish coalescing — those have the highest immediate impact. Then add destructuring defaults to your function signatures. The rest will follow naturally as you encounter 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.
Frequently Asked Questions
What are the most useful JavaScript tricks for beginners?
Optional chaining, nullish coalescing, destructuring with defaults, and array methods (map/filter/find). These four patterns improve code quality immediately.
What is optional chaining in JavaScript?
?. safely accesses nested properties — returns undefined instead of throwing if any level is null/undefined.
What is short-circuit evaluation?
JavaScript stops evaluating expressions as soon as the result is known. && stops at the first falsy value; || stops at the first truthy value. Enables concise conditional logic.
How do I write cleaner JavaScript?
Use const by default, destructure instead of repetitive property access, prefer array methods over for loops, and name everything clearly.
Frequently Asked Questions
AiTechWorlds Team
✓ Verified WriterThe AiTechWorlds team is passionate about AI, technology, and education. We create high-quality, research-backed content to help you learn, grow, and succeed in the modern digital world.
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 2025?
GraphQL vs REST API compared honestly for 2025: 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.