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'
π‘ 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'
π‘ 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'
π‘ 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]]
π‘ 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' }
π‘ 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)