DEV Community

Sahil khatiwada
Sahil khatiwada

Posted on

🌟 5 JavaScript Tricks Every Developer Should Know!

Hey Devs! πŸ‘‹
JavaScript is powerful, and sometimes, small tricks can make a big difference in writing clean and efficient code. Here are 5 awesome JavaScript tricks you might not know (or maybe forgot)! πŸ€“

1️⃣ Optional Chaining (?.)
Access deeply nested properties without worrying about undefined.

const user = { profile: { name: "Sahil" } };

// Without optional chaining
const userName = user.profile ? user.profile.name : undefined;

// With optional chaining πŸŽ‰
const userName = user?.profile?.name; // 'Sahil'
Enter fullscreen mode Exit fullscreen mode

πŸ’‘ Why it’s useful: No more crashing apps when accessing nested properties!

2️⃣ Nullish Coalescing (??)
Provide a fallback value only for null or undefined.

const value = null;
const result = value ?? "Default Value"; // 'Default Value'

Enter fullscreen mode Exit fullscreen mode

πŸ’‘ Why it’s useful: Avoid using || when 0, false, or '' are valid values.

3️⃣ Destructuring with Defaults
Set default values when destructuring objects.

const settings = { theme: "dark" };
const { theme = "light", layout = "grid" } = settings;

console.log(theme);  // 'dark'
console.log(layout); // 'grid'

Enter fullscreen mode Exit fullscreen mode

πŸ’‘ Why it’s useful: Makes your code clean and concise!

4️⃣ Array .flat()
Flatten nested arrays with a single method.

const numbers = [1, [2, [3, [4]]]];
const flatNumbers = numbers.flat(2);

console.log(flatNumbers); // [1, 2, 3, [4]]

Enter fullscreen mode Exit fullscreen mode

πŸ’‘ Why it’s useful: Easy handling of multi-dimensional arrays.

5️⃣ Dynamic Object Keys
Use expressions to dynamically set object keys.

const key = "name";
const user = { [key]: "Sahil" };

console.log(user); // { name: 'Sahil' }

Enter fullscreen mode Exit fullscreen mode

πŸ’‘ Why it’s useful: Perfect for dynamic use cases like creating objects from API responses.

Share Your Favorite Tricks!
Have a favorite JavaScript trick? Drop it in the comments below! Let’s level up our JavaScript game together. πŸš€

Top comments (0)