Wednesday, December 4, 2013

Why not to use new Array()?

Yeh, why not? Simple. Take an example below and please be patient, I'm going somewhere with this:

function orderBeers()
// drinking beer, around 10 beers usually does it
return 10; 

The code above creates a function, but more importantly it creates orderBeers property on global object which in browser environment happens to be a window.

Now, global object has heaps of properties e.g. locationprint and among many others Array. We use this all the time without much thinking. So our orderBeers property references the function we just created.

Ok, so now some malicious, no beer drinking programmer might not agree with our beer drinking policy and might override our function so it returns 0:

function orderBeers()
// no beer for anyone
return 0;

And there goes our fun. Now, think about this. We can do it with our orderBeers function and so we can do it with Array, right? Take this code:

function Array() {
// some code

var myArray=new Array();

Instead of JS Array we will get Array object we defined. This will not happen when we use [] syntax:

var myArray=[];

Ok, who would o such a thing you ask? Well, although this is unlikely in my opinion however its important to understand why this is possible. 

No comments:

Post a Comment