DEV Community

Discussion on: The shortest way to conditional insert properties into an object literal

Collapse
 
konrud profile image
Konstantin Rouda

Interesting trick, but what if our value is 0 which can be a valid value to use? So our code:

𝐯𝐚𝐫 𝐜𝐨𝐢𝐧𝐬 = 𝟎;
𝐯𝐚𝐫 𝐨𝐛𝐣 = {
  𝐧𝐚𝐦𝐞: "𝐉𝐨𝐡𝐧",
  ...𝐜𝐨𝐢𝐧𝐬 && { 𝐜𝐨𝐢𝐧𝐬𝐀𝐦𝐨𝐮𝐧𝐭: 𝐜𝐨𝐢𝐧𝐬 }
}
Enter fullscreen mode Exit fullscreen mode

won't copy anything.

Collapse
 
jfet97 profile image
Andrea Simone Costa • Edited

So there is no point to use the trick in this way if 0 is a valid amount as well.

Remember that on the left you put the condition, so you may write like the following:

𝐯𝐚𝐫 𝐜𝐨𝐢𝐧𝐬 = 𝟎;
𝐯𝐚𝐫 𝐨𝐛𝐣 = {
  𝐧𝐚𝐦𝐞: "𝐉𝐨𝐡𝐧",
  ...𝐜𝐨𝐢𝐧𝐬>=0 && { 𝐜𝐨𝐢𝐧𝐬𝐀𝐦𝐨𝐮𝐧𝐭: 𝐜𝐨𝐢𝐧𝐬 }
}
Collapse
 
tkane2000 profile image
tkane2000

you could pass coins to a method that checks for false, null, and undefined only (or something along those lines)

Collapse
 
kaptenadhoc profile image
Reply guy 🤷‍♂️ • Edited

Just make sure to internalize what JavaScript considers truthy and you won't think this is a "gotcha" anymore.

So in your specific case you'd probably want to do something like

const coins = 0;
const obj = {
  name: "John",
  ...typeof coins === "number" && !isNaN(coins) && {coins},
};
Enter fullscreen mode Exit fullscreen mode
Collapse
 
konrud profile image
Konstantin Rouda

AFAIK, this is considered as a bad practice to use typeof to check the number, as NaN is also has type number (e.g. typeof NaN === "number"; // -> true). Moreover, typeof when used against number will return number, as a result, in lower case (i.e. not Number but number).

Thread Thread
 
kaptenadhoc profile image
Reply guy 🤷‍♂️

Yeah the casing of number was just a typo. Adjusted it to check for NaN.