🚀 10 Favorite JavaScript Tips and Tricks to Boost Your Productivity

PriyaPriya
3 min read

JavaScript is an incredibly powerful and flexible language. But with great power comes great... verbosity—unless you know a few clever tricks! In this post, I’ll walk you through 10 of my favorite JavaScript tips and tricks that can help you write cleaner, shorter, and more readable code.


đź”— 1. Optional Chaining and Nullish Coalescing

Dealing with deeply nested objects? Say goodbye to && chains and hello to this combo:

const username = user?.profile?.name ?? 'Guest';

âś… This checks for user.profile.name safely, and falls back to 'Guest' if it's null or undefined.


🔄 2. Swap Variables Without a Temp Variable

Remember the old way?

let temp = a;
a = b;
b = temp;

Here's the modern approach:

[a, b] = [b, a];

Simple and elegant!


🔥 3. Remove Duplicates from an Array

Duplicates? Not on your watch:

const unique = [...new Set([1, 2, 2, 3, 4, 4])]; 
// [1, 2, 3, 4]

Using Set ensures uniqueness, and the spread operator converts it back to an array.


đź§  4. Convert Any Value to Boolean

const isAvailable = !!value;

Two bangs (!!) convert anything into a true or false. Handy for quick checks.


✨ 5. Default Function Parameters

Instead of:

function greet(name) {
  name = name || "Stranger";
  console.log(`Hello, ${name}`);
}

Use:

function greet(name = "Stranger") {
  console.log(`Hello, ${name}`);
}

Much cleaner and easier to read.


đź§ą 6. Filter Falsy Values from an Array

Want to clean an array of null, undefined, false, 0, '', or NaN?

const cleaned = arr.filter(Boolean);

Elegant one-liner for array sanitization!


📦 7. Use Object Property Shorthand

const name = 'Alice', age = 30;
const user = { name, age };
// Instead of: { name: name, age: age }

Great when variable names match object keys.


🔍 8. Destructure Like a Pro

Destructuring makes your code concise and readable:

const { title, author } = book;
const [first, second] = list;

It even works in function parameters!


đź§Ş 9. Dynamically Set Object Keys

Need to use a variable as an object key?

const key = "status";
const obj = { [key]: "active" };
// { status: "active" }

Perfect for building flexible data structures.


đź”— 10. Merge Arrays and Objects Easily

const all = [...arr1, ...arr2];
const settings = { ...defaultSettings, ...userSettings };

Use spread syntax to combine arrays or override object properties.


đź’¬ Final Thoughts

These small improvements can add up to big gains in readability, maintainability, and joy while writing JavaScript. Whether you’re a beginner or a seasoned developer, mastering these tricks can make your code feel more modern and elegant.

0
Subscribe to my newsletter

Read articles from Priya directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Priya
Priya