DEV Community

Discussion on: Mastering JavaScript Shorthands

Collapse
 
efpage profile image
Eckehard

Version 3 may cause trouble, as shorthand behaves differently:

function test(name1, name2 = 'Guest') {
   name1 = name1 || 'Guest';
   console.log(name1, name2)
}
    test("test", "test") // -> test test
    test() // -> Guest Guest
    test(false, false) // -> Guest false
    test(null, null) // -> Guest null
    test(0, 0) // -> Guest 0
Enter fullscreen mode Exit fullscreen mode

Default function parameters are used, if the argument is undefined, while the || checks for false. In Javascript, any nullish value is treated as false.

It work better, if you use nullish coalescing operator (??), but even that fails if you provide null as an argument (which usually does not happen accidentially):

    function test(name1, name2 = 'Guest') {
      name1 = name1 ?? 'Guest';
      console.log(name1, name2)
    }
    test(null, null) // -> Guest null
Enter fullscreen mode Exit fullscreen mode

In most cases the default parameters are the better solution, but there are situations where you need to set defaults in your code. It seems, there is no shorthand for all cases:

   name1 = typeof(name1) !==='undefined' ?  name1 : 'Guest';
   if (typeof(name1) !==='undefined' ) name1  =  'Guest'
  // ----- use a default() function --------
   const default = (val, def) => 
        (typeof(val) === 'undefined') ? def : val

   val = default(val, "Guest") // 
Enter fullscreen mode Exit fullscreen mode
Collapse
 
leandro_nnz profile image
Leandro Nuñez

Thanks! I linked a caution to this excellent explained comment.