There are so many ways to loop through an array or object in Javascript, one of them is using for .. in
.
For example:
1 2 3 4 5 6 7 8 9 10 11 12 |
var arr = ['David', 'John', 'Tom', 'Peter']; for ( var i in arr ) { console.log( arr[i] ); } /* Output: David John Tom Peter */ |
It looks correct, right? But if someone accidentally adds a property to Array.prototype
somewhere in your project:
1 |
Array.prototype.anyName = 'Matt'; |
The output will be:
1 2 3 4 5 |
David John Tom Peter Matt |
This is totally wrong, how can we prevent this issue? The answer is using hasOwnProperty
method to check:
1 2 3 4 5 |
for ( var i in arr ) { if ( arr.hasOwnProperty( i ) ) { console.log( arr[i] ); } } |
By using this trick, you don’t have to worry when using for .. in
.
Thanks for reading and happy coding!