Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When using object destructuring assignment, why is a property "name" cast to string? [duplicate]

Given

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

Why is name identifier cast to string when using var at object destructuring assignment?

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 defining a different identifier

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

though curious as to the significance of var returning different results than let or const for the name identifier at a browser environment?

like image 920
guest271314 Avatar asked Jun 07 '17 05:06

guest271314


1 Answers

This behaviour is defined by the scope in which the code is being executed.

name refers to window.name property, which descriptor has a setter to convert it to string when being assigned as window.name = 1:

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

When being executed in global scope, var name = ... assigns a value to window.name. While let and const declare block-scoped variables.

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

(() => {
 var obj = {name: 1};
 var {name} = obj; 
 console.log(typeof name); // 'number'
})();
like image 68
Estus Flask Avatar answered Sep 28 '22 00:09

Estus Flask