DEV Community

Sahil khatiwada
Sahil khatiwada

Posted on

1

๐ŸŒŸ 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. ๐Ÿš€

Image of Timescale

๐Ÿš€ pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applicationsโ€”without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more

Top comments (0)