Forem

Cover image for Top 10 JavaScript Hacks Every Developer Should Know
Abhay Singh Kathayat
Abhay Singh Kathayat

Posted on

Top 10 JavaScript Hacks Every Developer Should Know

JavaScript is one of the most versatile and widely-used programming languages in the world. Whether you're building a simple website or a complex web application, knowing a few clever JavaScript hacks can save you time, improve your code's efficiency, and make you a more effective developer. In this article, we’ll explore 10 JavaScript hacks that every developer should know.


1. Destructuring Assignment for Cleaner Code

Destructuring allows you to extract values from arrays or objects into distinct variables. This can make your code cleaner and more readable.

// Object Destructuring
const user = { name: 'John', age: 30 };
const { name, age } = user;
console.log(name); // John
console.log(age);  // 30

// Array Destructuring
const numbers = [1, 2, 3];
const [first, second] = numbers;
console.log(first); // 1
console.log(second); // 2
Enter fullscreen mode Exit fullscreen mode

2. Optional Chaining (?.)

Optional chaining is a lifesaver when dealing with nested objects. It prevents errors when trying to access properties of undefined or null.

const user = { profile: { name: 'Alice' } };
console.log(user.profile?.name); // Alice
console.log(user.settings?.theme); // undefined (no error)
Enter fullscreen mode Exit fullscreen mode

3. Nullish Coalescing Operator (??)

The nullish coalescing operator (??) is a logical operator that returns the right-hand side operand when the left-hand side is null or undefined.

const foo = null ?? 'default';
console.log(foo); // 'default'

const bar = 0 ?? 'default';
console.log(bar); // 0 (because 0 is not null or undefined)
Enter fullscreen mode Exit fullscreen mode

4. Short-Circuit Evaluation

Use logical operators (&&, ||) for concise conditional logic.

// Instead of:
if (isLoggedIn) {
  showDashboard();
}

// Use:
isLoggedIn && showDashboard();

// Default values:
const username = user.name || 'Guest';
Enter fullscreen mode Exit fullscreen mode

5. Template Literals for Dynamic Strings

Template literals (backticks) make it easy to create dynamic strings without messy concatenation.

const name = 'John';
const age = 30;
console.log(`My name is ${name} and I am ${age} years old.`);
Enter fullscreen mode Exit fullscreen mode

🔗 Read the full article on Medium: Top 10 JavaScript Hacks Every Developer Should Know

Happy coding! ✨

Top comments (0)