Posted in Javascript

Safest way when using for .. in to loop through an array or object in Javascript

Safest way when using for .. in to loop through an array or object in Javascript Posted on August 12, 2017Leave a comment

There are so many ways to loop through an array or object in Javascript, one of them is using for .. in.

For example:

It looks correct, right? But if someone accidentally adds a property to Array.prototype somewhere in your project:

The output will be:

This is totally wrong, how can we prevent this issue? The answer is using hasOwnProperty method to check:

By using this trick, you don’t have to worry when using for .. in.

Thanks for reading and happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *