0

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?

Raymon Opie
  • 237
  • 1
  • 9
  • No, they don't. Where as your code searches for the property form the entire object, including the prototype chain, and checks the value of that property, `hasOwnProperty` method checks only the own properties of the object, and the existense of the property. Most of the time you need own properties only, but there are use cases where you need to check the inherited properties too, though this would be simpler by using `in`. – Teemu Jan 17 '19 at 06:37
  • 1
    Technically `wheels` is not inherited here, you're just copying that as an own property. The usefulnes of the own property check is often coming along libraries, if a library has added, say a method called `foo`, to the `Object` constructor prototype, you would get that property every time you'll iterate any object, including your simple data objects, even they'd been created on the fly and passed as an argument. – Teemu Jan 17 '19 at 07:14
  • gotcha, thank you the follow up @Teemu – Raymon Opie Jan 17 '19 at 07:16
  • Notice also, that the first code snippet gives wrong results when a property under check contains a falsy value. A simple existense check would be `if (key in obj)`, but as said before, also the properties in the prototype chain are accepted. – Teemu Jan 17 '19 at 07:28

0 Answers0