I have a code implementation that iterates over an object
's properties.
for (const prop in obj) {
propsMap[prop] = prop;
}
But as is states, my IDE (WebStorm) adviced me to add a property check using obj.hasOwnProperty(prop)
to avoid iterating over inexistant properties:
for (const prop in obj) {
if (obj.hasOwnProperty(prop)) {
propsMap[prop] = prop;
}
}
The problem is that the current tests always come with obj.hasOwnProperty(prop)
being true
and the coverage is not the best I could get and I don't know what could happen if obj
does not actually have the property prop
.
To test this you could create object that inherits something from its prototype
const obj = Object.create({name: 'inherited'})
name
will falsyfy obj.hasOwnProperty('name')
check.
But there are better options to copy object. For example Object.assign
Object.assign(propsMap, obj)
Also you should keep in mind that obj.hasOwnProperty
check is error prone. For example
const obj = {hasOwnProperty: null} // hasOwnProperty is not a function
const obj = Object.create(null) // obj wont inherit hasOwnProperty
so atleast replace it with
const hasOwnProperty = {}.hasOwnProperty
for(const name in obj) {
if(hasOwnProperty.call(obj, name)) {
}
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