krave krave - 3 months ago 4x
Javascript Question

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 =
} = {},
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!


This code is using destructuring as mechanism for deep-merging objects. It's weird, don't do it.

To answer your question directly:

What is the difference between config.options.enable and other properties of config.options?

There's no difference. The author is using config.options.enable to refer to ALL of the lines that look like config.options.x = defaults.options.x.