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?
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'
})();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With