Securing Undefined Variable In Javascript

Sep 26, 2011 No Comments by Mahdi Pedram

Sometimes some bad programmer or some hacker messes up with the undefined global variable in javascript.
so why would we really care about it.

the following are some examples that the variable undefined will be returned

 
 
var myVar = undefined; //Anything that has been set to the value of undefined.
 
function test(){}; console.log( test() ); // returns undefined - Implicit returns of functions due to missing return statements.
 
function test(){ return; }; console.log( test() ); // returns undefined - return statements which do not explicitly return anything.
 
function test(a,b){ console.log(a); }; test(); // returns undefined - Function parameters which do not had any explicit value passed.
 
var obj = { a: 'test' }; console.log(obj.b); // returns undefined - Lookups of non-existent properties.
 

the undefined variable has a copy of the actual value of undefined, but if someone overwrite the value of undefined variable, that might be insecure for our code.
so how could we get around this.

the answer is: Putting our code in a self-Invoking function.

 
var undefined = "new Value";
(function(input1, input2, undefined) {
console.log(undefined); // returns undifined
})(1,2);
 

this might be a neat trick if you check jQuery source code. they are also using it.

javascript

About the author

I'm Web Developer , I spent most of my time on programming web applications ,I'm both Front-end , Back-end Developer . Coding is part of my life , I don't do programming for life , I am alive to Code
No Responses to “Securing Undefined Variable In Javascript”

Leave a Reply