Question

We can create an array in a couple of ways:

var myArray = new Array();

Or:

var myArray = [];

The second way is safer to use than the new Array() syntax, because the Array constructor can be overwritten and potentially replaced with malicious code.

I have seen above lines in many JavaScript books but I don't understand how an Array constructor can be overwritten and replaced with malicious code? I'm looking for an example of how someone can do it, so that I can understand the reality of the issue.

Was it helpful?

Solution

Somewhere in the code above:

Array.prototype.forEach = function (e){
  console.log("something wrong there");
  return(e);
};

Somewhere in the code below:

var i = [1,2,3,4,5];
i.forEach(function(e){
  console.log(e);
});

Output:

>"something wrong there"

As you can see, there is no difference how to initialize array variable. var i = []; just shorter notation.

OTHER TIPS

If you write on your JS console :

[1,2,3]

(just like that) - you can do nothing with it.

Well that's not accurate with old browsers.

You could overload the array ctor by :

Array = new function (){... }

and so , when you got your friend list via Json ( not jsonp) : -

someone could use an XSS/XSF attack and steal your friends list.

The thing ere is the fact that : if you write [1,2,3] - there is actually a ctor working here.

So if you got to a website which does array response - he could still your list.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top