How can the variable
name
be redefined?
It isn’t.
What’s with the left to right assignment? Doesn’t = work right to left?
Yes, and that’s what’s happening here. That’s destructuring assignment. This one line:
const {key1: value1, key2:value2} = name
is the equivalent of this:
const value1 = name.key1;
const value2 = name.key2;
You’re quite right that it looks like an object being assigned to a variable, but in reverse. That’s intentional. When you do:
const x = {a: 1, b: 2};
you’re creating an object (putting together a structure) and assigning it to x
. When you do:
const {a: vara, b: varb} = x;
you’re destructuring (taking a structure apart) the object on the right into the targets (vara
and varb
) on the left. The syntax for this is identical, just reversed. Both forms also have a shorthand version:
const a = 1;
const b = 2;
const x = {a, b};
creates an object with a
and b
properties (with the values from the a
and b
in-scope identifiers). This;
const {a, b} = x;
takes a
and b
properties from x
and uses it to set the value of the constants a
and b
.
I should note that nothing about destructuring is tied to let
or const
(or var
). Just like you can use any in-scope variable or a property to provide the value for an object property when creating an object, you can do the same when destructuring. Because object destructuring starts with {
, if you’re not doing it in an expression you need to put a (
in front of it so the {
doesn’t look like the beginning of a block:
const x = {a: 1, b: 2};
let a, b;
({a, b} = x);
console.log(a, b); // 1 2
const y = {};
({a: y.ayyy, b: y.beee} = x);
console.log(y); // {ayyy: 1, beee: 2}
what
name
is referenced in the line marked ***? The one initially passed or the object created?
There is no object created in that code. (Well, the arrow function is an object, and there are behind-the-scenes specification-level objects like the lexical environment, but…)
It’s impossible to say what name
is in the line you’ve marked because that’s a syntax error, the function
keyword starts a function declaration that’s never finished. If by function(name)
you meant someFunction(name)
, it would be the name
passed into the arrow function.
0
solved What is this form or syntax called in javascript? [closed]