Ele
Ele

Reputation: 33726

Exactly how do destructuring assigments in function arguments work?

I don't understand why the destructuring logic in the call of the function is actually declaring a new variable.

function fn() {}
let object = {x: "Ele", y: "From", z: "Stack"};

fn({x} = object);

console.log(x);

And secondly, what's the problem in the logic below. I'm getting Uncaught ReferenceError: x is not defined. However, when I'm using var works fine.

function fn() {}
let object = {x: "Ele", y: "From", z: "Stack"};

fn({x} = object);

let x = "Dummy";
console.log(x);

I have a lack of knowledge with the previous logics.

Upvotes: 2

Views: 119

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1074335

...actually declaring a new variable

It's what I call The Horror of Implicit Globals. This line:

fn({x} = object);

is effectively:

({x} = object);
fn(object); // a bit of hand-waving here, but roughly speaking...

Since it's assigning to an undeclared variable, it creates a global. If you were using strict mode, you would have gotten a ReferenceError instead:

"use strict";

function fn() {}
let object = {x: "Ele", y: "From", z: "Stack"};

fn({x} = object);

console.log(x);

The result of an assignment is the value being assigned. In the case of a destructuring assignment, the value being assigned is the thing being destructured (the value of object, in your case).

...secondly, what's the problem in the logic below. I'm getting Uncaught ReferenceError: x is not defined

The problem when you add let x is that the line assigning to x is now in the Temporal Dead Zone for the declaration of x. x is reserved at that point, but not initialized. The error message says "not defined" because the let x line hasn't been executed yet. As though you had:

x = 0;
let x;

Upvotes: 6

Jonas Wilms
Jonas Wilms

Reputation: 138267

To answer the second question first: You cannot use a variable declared with let (x in this case) before it was declared. When doing { x } = you do destructure into x.

Now when you do fn({ x } = object) that is basically a function call with its first argument being an assignment expression, and that always evaluates to the result of the right hand-side. a=b evaluates to b, {x} = object evaluates to object.

I don't understand why the destructuring logic in the call of the function is actually declaring a new variable.

Any assignment to an identifier that was not declared yet does create a global variable implicitly. "use strict" mode to prevent that.

Upvotes: 2

Related Questions