K. Güler K. Güler - 4 months ago 9
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
foobar
property of the window object?

Why is a custom global function like
foobar
protected against
delete
operator, but a built-in global function like
alert
not?

Answer

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