Skip to content

Latest commit

 

History

History
26 lines (19 loc) · 933 Bytes

destructuring.md

File metadata and controls

26 lines (19 loc) · 933 Bytes

Destructuring

Destructuring assignment allow us to assign properties of arrays or objects to variables.

WTF

function foo(x = {y: 10}, {y = 20} = {}) {
    console.log(x.y, y);
}

foo();                  // 10 20
foo({y: 30}, {y: 40});  // 30 40
foo({}, {});            // undefined 20

Why?

The inconsistency is on the last line with foo({}, {})'s result of undefined 20.

Our first argument {} is able to override the default value of {y: 10}. x.y logs undefined.

However, our second argument {} is not able to override our variable y and not having it declared.

The inconsistency comes because the syntax is quite similar but the behaviour varies depending on the way we do destructuring.

Further Reading