I am mystified by the fact that when I create a new Error object I can see its message or name, but I can\'t see a list of its keys by using the standard ways. Why is that?
JavaScript properties may be non-enumerable, which means they does not appear in for..in
loops or Object.keys
results.
You can use Object.getOwnPropertyNames to get all properties (enumerable or non-enumerable) directly on an object. I say "directly" because normal enumeration looks up the object's prototype chain to get enumerable properties on parent prototypes, while getOwnPropertyNames
does not.
Thus, Object.getOwnPropertyNames(err)
only shows
['stack',
'arguments',
'type',
'message']
The name
property is a non-enumerable property of Error.prototype
and is never set directly on an Error
instance. (Prototyping recap: when you try to access err.name
, the lookup err
turns up nothing, so the interpreter looks at Error.prototype
, which does have a name
property.)