0

I am working with another developer's code and have found this construct. The code seems to be instantiating an object within a function's argument list. I would like to read about this. What is the name of this construct? What is its purpose?

function FooBar( { Foo = 'Bar' } = {} ) {
   console.info(Foo);
}

FooBar();
FooBar('Baz');
FooBar(Foo = 'Baz');
FooBar({Foo : 'Ah! This is the one!'}); // <--- not like the others
FooBar( { Foo = 'Baz' } = {} );

Here are my thoughts:

  • { Foo = 'Bar' } seems to be creating a new object with a single property.
  • = {} seems to be assigning a new object to that object? What? Why?
  • Could we not just set var Foo = 'Bar' inside the function body?
  • Is the construct instead a way of defining a default value for a parameter?

This is the actual code:

import Leaflet from 'leaflet';

export function configure(
  frameworkConfig, 
  { LeafletDefaultImagePath = 'some/path' } = {}) {
    Leaflet.Icon.Default.imagePath = LeafletDefaultImagePath;
    frameworkConfig.globalResources('./leaflet.js');
}
Shaun Luttin
  • 133,272
  • 81
  • 405
  • 467
  • Are you confused about the part before or after the equals sign, or everything? – Bergi Jun 15 '16 at 16:59
  • The part that seems odd to me is the creation of a new object within the functions argument list. – Shaun Luttin Jun 15 '16 at 17:01
  • 1
    It's a new ES6 feature that allows you to define default values for function parameters: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Default_parameters – forrert Jun 15 '16 at 17:04
  • @forrert Doesn't that mean the above FooBar function should have an empty object as its default? – Shaun Luttin Jun 15 '16 at 17:06
  • @ShaunLuttin: Exactly that's what it means. When you call `FooBar()` or `FooBar(undefined)` it will create that empty object, and use it as the value for the `{ Foo = 'Bar' }` destructuring expression. – Bergi Jun 15 '16 at 17:07
  • 1
    It doesn't create the empty object, though. When we run the snippet, it creates an object with a `Foo` property that has `'Bar'` as its value. – Shaun Luttin Jun 15 '16 at 17:08
  • 1
    It looks like `{ Foo = 'Bar' } = {}` makes it so you *can't* change the value of `Foo` my passing in a parameter. Try running: `FooBar('Baz');` – gen_Eric Jun 15 '16 at 17:10
  • 1
    I think `{ Foo = 'Bar' }` *may* be interpreted as a *block statement*, setting a variable `Foo`. I'm not sure what the `= {}` part does. – gen_Eric Jun 15 '16 at 17:11
  • This might be call object destructuring https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Object_destructuring – Shaun Luttin Jun 15 '16 at 17:15

0 Answers0