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?
> err = new Error("an error") [Error: an error] > err.message 'an error' > err.name 'Error' > Object.keys(err) [] > JSON.stringify(err) '{}'
How to Check if an Object Has a key in JavaScript with the in Operator. You can use the JavaScript in operator to check if a specified property/key exists in an object. It has a straightforward syntax and returns true if the specified property/key exists in the specified object or its prototype chain.
Undefined value primitive value is used when a variable has not been assigned a value. The standard clearly defines that you will receive undefined when accessing uninitialized variables, non-existing object properties, non-existing array elements, and alike.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With