Hacker News new | ask | show | jobs
by simon_renoult 4541 days ago
Why using :

    function doFoo(bar) {
      bar = (bar !== undefined) ? bar : "default_value";
    }
Over :

    function doFoo(bar) {
      bar = bar || "default_value";
    }
Coercion avoidance ?
3 comments

The second function sets bar to "default_value" if called with a falsy argument like 0 or an empty string.
Yes, the second option is better in most cases. I'd spend more time reading the first one to understand what is going on compared to the second option.

Keep in mind that you will have to go for the first option (or other better options) if you expect 'falsy' values to be passed as arguments.

0 is falsy in javascript; with the second method, default_value will get used instead.
I'd use:

  bar = bar != null ? bar : 'default';