Hi, nice to meet you ๐!
You can find this article in my personal blog here.
For further actions, you may consider blocking this person and/or reporting abuse
Hi, nice to meet you ๐!
You can find this article in my personal blog here.
For further actions, you may consider blocking this person and/or reporting abuse
Latest comments (48)
I'm a year to late at the party, but thank you very much for the good explanation. I was in search for exactly this feature and it is an elegant and modern solution!
Thanks!
~semplicity~ simplicity
For added fun with this, I tried a couple of things:
Personally, I would do it like
...(obj && { props: foo})
so it is obvious how the operators work, people who don't immediately know that&&
has precedence over...
won't read the code as easily.This seems much nicer than my current
const obj = { ...{ condition? { prop: value }: {} }};
๐คWhile it's not entirely clear at first glance how it works, I think the intent is clear enough for someone stumbling across it (excusing any bugs caused by gotchas)
I know how && works, but wtf does ... do?
Google rest/spread operators ๐
It unpacks stuff, like * in Python, which "spread" could be a synonym for, but "rest operator"? googles Ah, as in "remaining parameters".
Mind blown!
Basically, it evaluates like this:
...(condition && { prop: value }),
Very helpful what Stan posted here. Parenthesis really help. Actually they are a default lint recommendation in this specific case. I think adding them to the code in the article would help a lot.
But it wouldn't be the shortest anymore ;)
hey man! I'm trying to help you here! lol...great article!
It's a useful trick! There are a bunch of others at blog.bitsrc.io/6-tricks-with-resti... (not my post), including a concise way to remove properties from objects.
Interesting trick, but what if our value is 0 which can be a valid value to use? So our code:
won't copy anything.
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
AFAIK, this is considered as a bad practice to use
typeof
to check the number, asNaN
is also has typenumber
(e.g.typeof NaN === "number"; // -> true
). Moreover,typeof
when used against number will returnnumber
, as a result, in lower case (i.e. notNumber
butnumber
).Yeah the casing of
number
was just a typo. Adjusted it to check for NaN.you could pass coins to a method that checks for false, null, and undefined only (or something along those lines)
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: