Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Not able to understand this snippet about ES6 destructuring

I am reading the latest one of You Don't Know JS series and being completely lost when it goes to the destructuring part. Please help me to understand the snippet here please. The context here is about to put some specified configurations in effect while other defaults still available.

the defaults:

var defaults = {
    options: {
        remove: true,
        enable: false,
        instance: {}
    },
    log: {
        warn: true,
        error: true
    }
};

the config:

var config = {
    options: {
        remove: false,
        instance: null
    }
};

how does the author accomplish

config.options = config.options || {};
config.log = config.log || {};
({
    options: {
        remove: config.options.remove = defaults.options.remove,
        enable: config.options.enable = defaults.options.enable,
        instance: config.options.instance =
                      defaults.options.instance
    } = {},
    log: {
        warn: config.log.warn = defaults.log.warn,
        error: config.log.error = defaults.log.error
    } = {}
} = config);

and the author made such description about the snippet:

The previous snippet’s approach works because I’m hacking the destructuring and defaults mechanism to do the property === undefined checks and assignment decisions for me. It’s a trick in that I’m destructuring config (see the = config at the end of the snippet), but I’m reassigning all the destructured values right back into config, with the config.options.enable assignment references.

The most confused one is the last sentence: with the config.options.enable assignment references. What is the difference between config.options.enable and other properties of config.options?

Could you please do some explanation about the code and the descriptions for me? Thank you!

like image 780
krave Avatar asked Dec 24 '22 08:12

krave


1 Answers

It's a typo on my part. I just filed an issue to address it in the second edition. I should have said config.enable.XYZ to make it clear that I'm referring to all of them, not just that one. Sorry for my mistake causing you confusion.

like image 170
Kyle Simpson Avatar answered Jan 26 '23 00:01

Kyle Simpson