💡 JavaScript Hack: Conditionally Add Properties within Objects

Shameel Uddin - Sep 19 '23 - - Dev Community

🚀 Attention JavaScript Enthusiasts! 🚀

Are you tired of writing lengthy code to conditionally add properties to JavaScript objects? 😫 I've got an elegant shortcut for you that will not only simplify your code but also make it more readable and maintainable! 🤓✨

Traditional Approach:

Let's say you're working on a finance app, and you want to create an object representing a financial transaction with properties like transactionType, amount, and date. However, not all properties are relevant for every transaction, and you want to add them only if they exist.

Here's the traditional way to do it:

const transaction = {};

if (transactionType) {
  transaction.transactionType = transactionType;
}

if (amount) {
  transaction.amount = amount;
}

if (date) {
  transaction.date = date;
}
Enter fullscreen mode Exit fullscreen mode

The Elegant Shortcut:

JavaScript offers a concise and elegant solution to this problem using the spread (...) operator and object literal shorthand:

const transaction = {
  ...(transactionType && { transactionType }),
  ...(amount && { amount }),
  ...(date && { date }),
};
Enter fullscreen mode Exit fullscreen mode

Benefits of the Shortcut

Using this elegant shortcut offers several advantages:

  1. Conciseness: The code is much shorter and easier to read, reducing redundancy and improving maintainability.

  2. Scalability: It scales effortlessly as you add more properties or conditions without cluttering your code.

  3. Readability: The intent of your code is clearer, making it easier for others (and your future self) to understand.

Conclusion

This one-liner efficiently adds properties to your object if and only if they exist. It's shorter, more readable, and scales effortlessly as your codebase grows.

So, the next time you're working with JavaScript objects, remember this fantastic shortcut to streamline your code and impress your colleagues! 😎👨‍💼

I hope you learned something from this :-)

Follow me for more such content:
LinkedIn: https://www.linkedin.com/in/shameeluddin/
Github: https://github.com/Shameel123

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player