How to create objects in JavaScript: frontend vs backend

JavaScript developers, which one do you prefer? Creating objects is something we do all the time, and there are soooo many ways to do it in JavaScript. Here are the most common ones: In the frontend, I personally prefer spread + short-circuit, most of my objects are small and concise. In the backend, I usually go with Object.assign because it’s more easy to chain, and works well with larger or dynamic objects. 🚨 Shoutout to Kirill Kolomin for pointing this out, using && for conditional spreading can actually be a bit unsafe in option 1 when the value is falsy (like an empty string). A ternary operator (? :) is a safer choice.

  • text

Nice take! I also prefer spread syntax on the frontend, it’s clean and easy to read. Object.assign really shines when dealing with dynamic data 💡

Spread, although I learned it doesn't perform well in some cases, in which case `Object.assign` is the better option. In practice I tend to use spread unless there's many properties involved.

I usually follow the 1st option. I prefer to have "if" statements with code wrapped in a block, so 2nd option looks pretty, but doesn't much with my vision on it. By the way 2nd and 3rd options will cause errors in TS... and 1st as well. In TypeScript 1st option should cause an issue because it's not possible to spread from strings, only from objects. The way I usually do it is: const obj = { ...(email ? {email} : null) }

  • No alternative text description for this image
See more comments

To view or add a comment, sign in

Explore content categories