Conditionally Add Object Property in JavaScript with Spread Operator

💡JavaScript/React Tip💡 Ever wanted to conditionally add a property to an object in JavaScript without including it if it’s not needed? Here's a super clean trick using the spread operator! ✨ 👇 Check this out: As can be seen in the attached image, if the user object doesn't have both firstName and lastName, then the result object ❌ won’t include the userInfo property. ✅ But if both are present, userInfo gets added automatically! Simple, elegant, and clean⚡️ You can even add a specific name property conditionally if the value exists like this: const result = { ...(productData.name && { name: productData.name }), } 𝗙𝗼𝗿 𝗺𝗼𝗿𝗲 𝘀𝘂𝗰𝗵 𝘂𝘀𝗲𝗳𝘂𝗹 𝗰𝗼𝗻𝘁𝗲𝗻𝘁, 𝗱𝗼𝗻'𝘁 𝗳𝗼𝗿𝗴𝗲𝘁 𝘁𝗼 𝗳𝗼𝗹𝗹𝗼𝘄 𝗺𝗲. #javascript #reactjs #webdevelopment

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories