2

Imagine there is an object: foo = {"bar": 1}

Is there any benefit to use hasOwnProperty over dot-syntax to check for bar property inside foo object:

if (foo.hasOwnProperty('bar') {
  // do something
}

vs

if (foo.bar) {
  // do something
}

Also:

  • what will hapen if foo["bar"] is undefined?
  • what if foo undefined?
Oleksandr T.
  • 76,493
  • 17
  • 173
  • 144
0leg
  • 13,464
  • 16
  • 70
  • 94

1 Answers1

13

Look at this example,

Object.prototype.baz = 100;
var foo = {"bar": 1}

// will be false because in foo object there is no baz property 
// hasOwnProperty checks that the object has the specified property 
// and does not check that property in the prototype chain
if (foo.hasOwnProperty('baz')) {
  console.log('foo.hasOwnProperty("baz")');
}


//  will be true because baz property will be found 
//  in parent object through prototype chain
if (foo.baz) {
  console.log('foo.baz');
}
Oleksandr T.
  • 76,493
  • 17
  • 173
  • 144
  • strongly disagree. Better explanation here: https://stackoverflow.com/questions/7174748/javascript-object-detection-dot-syntax-versus-in-keyword – TheoNeUpKID Jan 20 '21 at 12:03