Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to overwrite the undefined in javascript?

Tags:

javascript

like

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

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

like image 670
Suraj Rawat Avatar asked Dec 19 '13 11:12

Suraj Rawat


People also ask

Can I return undefined in JavaScript?

An undefined variable or anything without a value will always return "undefined" in JavaScript. This is not the same as null, despite the fact that both imply an empty state. You'll typically assign a value to a variable after you declare it, but this is not always the case.

Does undefined === undefined in JS?

It's all still plain old JavaScript code running in a browser and undefined===undefined wherever you are. In short, you need to provide evidence that your object.

Does undefined occupy memory in JavaScript?

Per the specification there's only one undefined value but the specification does not require the implementation to hold a unique representation of undefined in memory. So any implementation can hold multiple copies of the value so long as the language semantics can be guaranteed.


2 Answers

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.

like image 170
Bergi Avatar answered Sep 30 '22 19:09

Bergi


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);
like image 23
gdoron is supporting Monica Avatar answered Sep 30 '22 19:09

gdoron is supporting Monica