K. Güler K. Güler - 1 year ago 59
Javascript Question

Weird behaviour with window object when removing property from it

function foobar() {}

console.log(typeof window.foobar); // "function"
console.log(typeof window.alert); // "function"

delete window.foobar;
delete window.alert;

console.log(typeof window.foobar); // "function"
console.log(typeof window.alert); // "undefined"

console.log(window.hasOwnProperty('foobar')); // true
console.log(window.hasOwnProperty('alert')); // false

Can somebody please explain, how this is possible?

Why can't I simply delete the
property of the window object?

Why is a custom global function like
protected against
operator, but a built-in global function like

Answer Source

Global variables are not configurable:

Object.getOwnPropertyDescriptor(window, 'foobar').configurable; // false

Therefore, delete won't work:

delete window.foobar; // false (in sloppy mode)
delete window.foobar; // TypeError (in strict mode)

That's why you should use strict mode. Otherwise some problems are silently ignored.

If you want to be able to delete the function, assign it as a property instead of using a function declaration:

window.foobar = function() {};
delete window.foobar; // true
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download