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?

Answers:

Answer

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);
Answer

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.

Answer

Yes it is possible to overwrite undefined.

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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.