Side-effect while extending the Array class
JavaScript No Comments »Let us assume, that you wrote some code to extend the Array class to a method. In this case we will add the min() method, which will return the lowest numeric value of all elements inside the array:
Array.prototype.min = function min(){ var returnValue = Number.MAX_VALUE; if(this.length === 0){ return false; } for(var i = 0; i < this.length; i++){ if(this[i] < returnValue){ returnValue = this[i]; } } return returnValue; };
This methods work fine, but you will notice a strange behavior if you cycle through all array elements using a for loop construct.
var list = [1, 2, 3]; for(var i in list){ console.log(list[i]); }
The code will produce this output:
1 2 3 min()
It seems that the for loop also iterates over the recently added method.
The method can only be removed from the Array class, not from an instance of it:
delete Array.prototype.min;
It can not be removed, but overwritten by assigning a value to it:
list.min = 0;
So, if you still want to use the for loop to iterate over the entries, you have to check the type of each entry:
for(var i in list){ if(typeof(list[i]) != 'function'){ console.log(list[i]); } }