Hacker News new | ask | show | jobs
by Sanddancer 4113 days ago
Personally, I would say

    foo = ('x' in bar) ? bar.x : 3;
instead. The problem with your code is that if the property bar.x exists, but is one of any number of values, like 0 or false, your code will still set foo to 3. Requiring properties to be explicitly created means that you're separating existence from value, which are two very different things in my book.
1 comments

Which are some of the most insidious bugs possible in JS. I shudder every time I see the syntax in your post's parent. It's a red flag. Your solution is good. I also use a lot of typeof(bar.x) !== 'undefined' since it's very explicit.
Every time?

I mean, very many times (for example) you're pulling in some JSON from a server app, which will have types properly enforced at the database and/or application level. There are still gotchas around defaulting to true, whether or not an empty string is a valid value and so on, but there are many cases where foo || bar is safe enough.

I have to disagree with you there. It's simply not a good idea to have a works-sometimes syntax for "if property is unset". The brevity doesn't make up for the fact that you sometimes have to fallback on the explicit check anyway. It may look clever but it's an abusage, and you're eventually going to get a production error, unless you're testing for it, and if you've got tests for that, brevity has already lost.
Well, I'm not responsible for your code, so you do whatever you want. But this, for me, is like being Van Halen and seeing brown M&Ms in the bowl. It's a red flag when I see that syntax in code that I should be much more defensive about what's happening everywhere else. There are no assurances about data, especially about data coming across the network.