Max
Max

Reputation: 2826

Is it possible to alter or delete properties of the global object in Javascript?

I was just reading up stuff about the global object, and was wondering if it would be possible to alter the values of the properties of the global object. I do not know what purpose this would serve, yet am interested.

Take this code for example:

Infinity = 4;           //Alter the property Infinity of the global object
                        //This doesn't prompt an error...
console.log(Infinity);  //Yet, for some reason it still prints Infinity, instead of 4.

Could you also do this:

delete Infinity;
console.log(Infinity)

It appears that this is impossible since Infinity still prints Infinity, instead of prompting an undefined error.

Upvotes: 3

Views: 62

Answers (2)

Scimonster
Scimonster

Reputation: 33409

It depends - is the property writable/configurable or not?

Infinity is neither, as exposed by the following console log:

> Object.getOwnPropertyDescriptor(window,'Infinity')
< Object {value: Infinity, writable: false, enumerable: false, configurable: false}

However, other global properties, such as frames, are configurable:

> Object.getOwnPropertyDescriptor(window,'frames')
< Object {value: Window, writable: true, enumerable: true, configurable: true}

So, basically, it depends on how the property is set up.

Upvotes: 1

Ian Hazzard
Ian Hazzard

Reputation: 7771

Good question, but the answer is no. Global objects cannot be modified or deleted. Global objects are required and built-in to JavaScript.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects

Upvotes: 0

Related Questions