10

like

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

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

Ashwini Agarwal
  • 4,828
  • 2
  • 42
  • 59
Suraj Rawat
  • 3,685
  • 22
  • 33

3 Answers3

11

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.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • 2
    +1. I think the confusion comes from thinking that `undefined` is a keyword instead of a property of the global object. Some syntax highlighters highlight it as if it were a keyword, probably adding to the confusion (even SO does this). – Dagg Nabbit Dec 19 '13 at 11:28
7

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);
gdoron
  • 147,333
  • 58
  • 291
  • 367
0

Yes it is possible to overwrite undefined.

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

Community
  • 1
  • 1
Richard Dalton
  • 35,513
  • 6
  • 73
  • 91