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.
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.