Search code examples
javascriptobjectecmascript-6destructuring

ES6 destructuring object assignment function parameter default value


Hi I was going through examples of object destructuring use in passing function parameters here Object Destructuring Demo

function drawES6Chart({size = 'big', cords = { x: 0, y: 0 }, radius = 25} = **{}**) {
  console.log(size, cords, radius);
 // do some chart drawing
}

 // In Firefox, default values for destructuring assignments are not yet  
 implemented (as described below). 
 // The workaround is to write the parameters in the following way:
   // ({size: size = 'big', cords: cords = { x: 0, y: 0 }, radius: radius =  
      25} = **{}**)

 drawES6Chart({
    cords: { x: 18, y: 30 },
    radius: 30
});

Can anybody let me know what is reason of using empty object assignment at the end of function parameter which I have marked in bold(embedded in double stars) above?


Solution

  • If you use it, and call the function with no parameters, it works:

    function drawES6Chart({size = 'big', cords = { x: 0, y: 0 }, radius = 25} = {}) {
      console.log(size, cords, radius);
     // do some chart drawing
    }
    
    drawES6Chart();

    if not, an error is thrown:

    TypeError: can't convert undefined to object

    function drawES6Chart({size = 'big', cords = { x: 0, y: 0 }, radius = 25}) {
      console.log(size, cords, radius);
     // do some chart drawing
    }
    
    drawES6Chart();