Suraj Rawat
Suraj Rawat

Reputation: 3763

Is it possible to overwrite the undefined in javascript?

like

function myFunction(){
    var undefined = "abc";
}

If its possible then how to restrict not to allow that?

Upvotes: 11

Views: 4485

Answers (3)

Bergi
Bergi

Reputation: 665130

Is it possible to overwrite the undefined in javascript?

If by "the undefined" you mean the global undefined variable, then no. Since EcmaScript 5, it is specified as non-writable. However, older browsers don't adhere that spec, so it is overwritable in legacy engines. You cannot really prevent it in them, but always reset it by undefined = void 0;. If you still worry and want to know how to protect your own scripts, check the question How dangerous is it in JavaScript, really, to assume undefined is not overwritten?.

like function myFunction(){ var undefined = "abc"; }

That's a different thing. You can always declare a local variable with the name undefined (shadowing the global one) and assign arbitrary values to it.

Upvotes: 12

Richard Dalton
Richard Dalton

Reputation: 35793

Yes it is possible to overwrite undefined.

This question has good solutions for working around that problem - How to check for "undefined" in JavaScript?

Upvotes: 0

gdoron
gdoron

Reputation: 150293

Some browsers allow it, the best way to restrict it is avoiding it.

But... some are using this technique to preserve the undefined:

(function(undefined){

})()

They get a variable called undefined but don't pass a value which gives undefined the undefined value.

From jQuery's source code:

(function( window, undefined ) {
    ...
    ...
})(window);

Upvotes: 8

Related Questions