News for hackers. Stuff that matters.
Re:Avoid Else, Return Early (2013) by timoxley on Monday March 26, 2018 @09:07AM (#16678538)
A big gotcha with `&&` as a guard in JS is that it can return any falsey typed value if you don't coerce the guard to a boolean.

e.g.

    const check(cond) => cond && otherValue
If `cond` is falsey, it returns `cond`.

This means the function could return any of: `false`, `undefined`, `null`, '', `0` or `NaN`.

This is a fairly common issue I see with React + JSX:

    <div>{cond && <SomeComponent />}</div>
If `cond` is `false`, `null`, `undefined` or '', everything will be just fine, but if `cond` happens to be a zero or `NaN`, suddenly you have a weird `0` or `NaN` rendering in your page. Oops.

Low cost, much safer guard:

    const check(cond) => !!cond && otherValue
Re:Avoid Else, Return Early (2013) by sergeykish on Monday March 26, 2018 @04:51PM (#16682469)
Quite interesting. For a moment I've thought it is another JS issue but no. It's React who's strange https://github.com/facebook/react/blob/v0.11.2/src/browser/u... https://github.com/facebook/react/blob/v0.11.2/src/utils/tra...

Same behavior on Ruby:

    def content_markup(children)
      case children
      when String, Numeric
        children
      when NilClass, TrueClass, FalseClass
        return
      else
        # ...
      end
    end

    content_markup 'foo'
    #=> "foo"
    content_markup 0
    #=> 0
    content_markup true
    #=> nil
    content_markup false
    #=> nil
    content_markup nil
    #=> nil
Re:Avoid Else, Return Early (2013) by Waterluvian on Monday March 26, 2018 @09:42AM (#16678758)
Good point. Good example. I imagine it works well in my cases but I haven't come across cases like your example where it breaks down.
Re:Avoid Else, Return Early (2013) by acjohnson55 on Monday March 26, 2018 @10:55AM (#16679343)
...until you do.

That's the problem with antipatterns. It's impossible to remain alert to the edge cases, and then they eventually bite you in production. Better to lint them away. But it's difficult to convince people not to do something really convenient if they haven't gotten bitten yet.

Re:Avoid Else, Return Early (2013) by sgustard on Monday March 26, 2018 @11:14AM (#16679488)
Yes, back when CoffeeScript was in vogue the ? operator handled this case nicely:

  cond? && otherValue