Even the best developers can benefit from learning lesser-known programming tricks to streamline their work and write better code. These insights can save you time, reduce bugs, and make your solutions more elegant. In this post, we’ll uncover eight practical yet hidden programming tricks that can transform how you approach coding.
1. Short-Circuiting for Cleaner Logic
Short-circuiting uses logical operators (&& and ||) to simplify code execution. This reduces verbosity and ensures cleaner conditions.
Example:
// Without short-circuiting
if (isLoggedIn) {
redirectToDashboard();
}
// With short-circuiting
isLoggedIn && redirectToDashboard();
// Default values with ||
const userName = inputName || 'Guest'; // Uses 'Guest' if inputName is falsy
Short-circuiting makes your code easier to read while maintaining clarity.
2. Use Destructuring for Simplicity
Destructuring allows you to unpack values from arrays or objects into distinct variables.
Example:
// Array destructuring
\const [first, second] = [10, 20];
// Object destructuring
const user = { name: 'Alice', age: 25 };
const { name, age } = user;
You can even rename variables or set default values:
const { name: userName = 'Guest' } = user;
3. Dynamically Create Properties with Computed Keys
Sometimes you need dynamic property names in objects. Use computed property keys to achieve this.
Example:
const key = 'favoriteColor';
const value = 'blue';
const userPreferences = {
[key]: value,
};
console.log(userPreferences); // { favoriteColor: 'blue' }
This is especially useful when building objects based on runtime values.
4. Memoize Expensive Function Calls
Memoization caches the results of function calls, improving performance for repeated calculations.
Example:
const memoize = (fn) => {
const cache = {};
return (...args) => {
const key = JSON.stringify(args);
if (!cache[key]) {
cache[key] = fn(...args);
}
return cache[key];
};
};
// Expensive computation
const slowSquare = (n) => {
console.log('Calculating...');
return n * n;
};
const fastSquare = memoize(slowSquare);
console.log(fastSquare(5)); // Calculating... 25
console.log(fastSquare(5)); // 25 (from cache)
5. Use Array Methods Wisely
Instead of for loops, modern array methods like .map(), .filter(), and .reduce() provide cleaner, functional solutions.
Example:
const numbers = [1, 2, 3, 4, 5];
// Map
const squares = numbers.map((n) => n * n); // [1, 4, 9, 16, 25]
// Filter
const evens = numbers.filter((n) => n % 2 === 0); // [2, 4]
// Reduce
const sum = numbers.reduce((acc, curr) => acc + curr, 0); // 15
These methods make your code concise and expressive.
6. Nullish Coalescing for Safer Defaults
The ?? operator is a safer alternative to || when setting defaults, as it only considers null and undefined as "falsy."
Example:
const userScore = 0;
const defaultScore = userScore || 10; // 10 (incorrect fallback)
const safeScore = userScore ?? 10; // 0 (correct)
Use ?? to avoid unintended behavior with valid falsy values like 0 or ' '.
7. Use Optional Chaining to Avoid Errors
Access deeply nested properties without fear of runtime errors using the ?. operator.
Example:
const user = { profile: { name: 'Alice' } };
// Without optional chaining
const userName = user && user.profile && user.profile.name;
// With optional chaining
const userName = user?.profile?.name;
console.log(userName); // 'Alice'
Optional chaining prevents unnecessary checks, improving code readability.
8. Make Objects Immutable with Object.freeze()
Freezing an object ensures its properties cannot be modified or added, making your code more predictable.
Example:
const config = Object.freeze({
apiUrl: 'https://api.example.com',
timeout: 5000,
});
config.timeout = 10000; // Ignored in strict mode
console.log(config.timeout); // 5000
Combine this with const for extra protection against accidental changes.
Final Thoughts
These programming tricks are small but mighty—adopting them can make a significant impact on your code quality and development speed.