When using an object destructuring assignment, why is the name property passed to a string?

Considering

let obj = {name: 1}; console.log(typeof obj.name, obj.name); // `"number"`, `1` 

Why is the name identifier passed to the string when using var when assigning destruction to an object?

 let obj = {name: 1}; var {name} = obj; console.log(name, typeof name); // `1` `string` 

But not using let or const ?

 let obj = {name: 1}; let {name} = obj; console.log(name, typeof name); 

We can avoid this unexpected result by specifying a different identifier.

 let obj = {name: 1}; var {name:_name} = obj; console.log(_name, typeof _name); 

although it is curious that the var value returns different results than let or const for the identifier name in the browser environment?

+7
javascript ecmascript-6
source share
1 answer

This behavior is determined by the area in which the code is executed.

name refers to the window.name property, the handle has a setter to convert it to a string when window.name = 1 assigned:

A valid browsing context name is any string with at least one character that does not start with a LOW LINE U + 005F character. (Names starting with an underscore are reserved for special keywords.)

When executed in the global scope, var name = ... assigns the value of window.name . For now, let and const declare variables with a block scope.

When executed in the local scope, name will refer to the local variable in both cases:

 (() => { var obj = {name: 1}; var {name} = obj; console.log(typeof name); // 'number' })(); 
+5
source share

All Articles