srgg6701
srgg6701

Reputation: 2048

JS window variables declaration and behavior

I have two global variables declared differently. I supposed that since both of them are properties of the window object, they should behave the same. But it is not. I can delete only one of them, that which was declared explicitly as a window property. That one which was declared by var operator cannot be deleted:

window.y1 = 'Y1';
"Y1"
var y2 = 'Y2';
undefined
y1;
"Y1"
y2;
"Y2"
window.y1;
"Y1"
window.y2;
"Y2"
delete window.y1;
true
delete window.y2;
false

It is not clear to me, why. Can you explain?

Upvotes: 1

Views: 23

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 371168

vars on the global object are non-configurable, which means they cannot be deleted:

var y2 = 'foo';
console.log(
  Object.getOwnPropertyDescriptor(window, 'y2')
);

Behavior is as expected. As MDN says:

Any property declared with var cannot be deleted from the global scope or from a function's scope.

On the other hand, explicitly assigning a property to an object does result in that property being configurable, by default:

window.y2 = 'foo';
console.log(
  Object.getOwnPropertyDescriptor(window, 'y2')
);

Upvotes: 1

Related Questions