I was just doing some practice questions and a question asked me to have a function that takes an object and a key and then checks if the key exists in the object. If so, return true, else return false so I wrote:
function check(obj,key) {
if (!!obj[key]) {
return true;
} else { return false}
}
The automatic checker kept saying this was incorrect. When I switched it to if (obj.hasOwnProperty(key)
, the test cases passed.
Aren't they accomplishing the same thing?
EDIT: I am seeing everyone say that hasOwnProperty
is necessary for checking a property isn't inherited as well. I tested that with this:
function Car() {
this.wheels = 4;
this.engines = 1;
}
function Ferrari() {
Car.call(this);
this.price = 200000;
this.color = 'red';
}
If I do let obj = new Ferrari()
then `obj.hasOwnProperty("wheels"), I get true back -- shouldn't that be coming back false since it's an inherited property?