Search code examples
javascriptecmascript-6destructuring

ES6 destructuring object, default value on assignment when not used as a function parameter?


I've got:

const fs = require('fs');

const packageConfig = JSON.parse(fs.readFileSync('./package.json'));
const { jspm: { configFile: jspmConfigFile }} = packageConfig;

but packageConfig's value for configFile could be undefined. In that case, I'd like to default jspmConfigFile to 'config.js

Is it possible to do this without creating an extended packageConfig object?

I realize I could do something like:

const { jspm: { configFile: jspmConfigFile }} = _.extend({
    jspm: { config: 'config.js'}
}, packageConfig);

but that's pretty messy just to get a sensible default with destructuring.

What am I missing?


Solution

  • The syntax for default values in object destructuring is:

    const { jspm: { configFile: jspmConfigFile = 'config.js' }} = packageConfig;
    

    But this is not yet implemented in Firefox: https://bugzilla.mozilla.org/show_bug.cgi?id=932080