Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why don't toString and hasOwnProperty (etc) show up in for-in loops in JavaScript?

I was talking about hasOwnProperty with another developer and how you are supposed to use it in for-in loops in javascript and he had a good question. When you do a for-in loop, why doesnt toString, hasOwnProperty, and other built in methods show up in the loop?

like image 939
Allen Rice Avatar asked May 27 '11 17:05

Allen Rice


1 Answers

The ECMAScript defines several properties for each property found on objects such as in prototypes. One of these is the enumerable property, and if it is set to false, then that property will be skipped.

You can actually manipulate these properties using the defineProperty function:

This method allows precise addition to or modification of a property on an object. Normal property addition through assignment creates properties which show up during property enumeration (for...in loop), whose values may be changed, and which may be deleted. This method allows these extra details to be changed from their defaults.

like image 97
Martijn Pieters Avatar answered Sep 22 '22 02:09

Martijn Pieters