1

So in the MDN documentation for destructuring function defaults it gives the following example.

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

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

However I can run this example with the first line as function drawES2015Chart({size = 'big', cords = {x: 0, y: 0}, radius = 25})

so leaving out the ={} part. I'm not sure why this works and what the advantages would be to using the longer form if the shorter form is in fact equally correct.

JZachary
  • 70
  • 7

3 Answers3

5

Refactoring the function as you suggest:

function drawES2015Chart({size = 'big', cords = {x: 0, y: 0}, radius = 25}) {
    console.log(size, cords, radius);
}

Would cause an error when attempting to call it with no arguments:

drawES2015Chart(); // throws TypeError

However, you may call it as:

drawES2015Chart({});

So, what the = {} is doing at the end is making you able to invoke

drawES2015Chart();

Which will be defaulted to

drawES2015Chart({});

Which will be defaulted to

drawES2015Chart({size = 'big', cords = {x: 0, y: 0}, radius = 25});
Matias Cicero
  • 25,439
  • 13
  • 82
  • 154
4

The final = {} defaulting the entire argument object to make sure you don't try to destructure undefined if someone called your function without any arguments at all (drawES2015Chart({}) vs drawES2015Chart())

If you didn't have this guard:

function foo({x = 10}) {
  return x;
}

foo(); // TypeError: can't convert undefined to object
foo({}); // 10
Matt
  • 43,482
  • 6
  • 101
  • 102
0

Try delete = {} and execute drawES2015Chart();

It prevents undefined from being destructured.

Reski
  • 169
  • 7