0

I'm writing an if statement for this exercise that will make something happen if an object has the specified property. My code was

if (obj.hasOwnProperty(prop)) {
    //do this

but the program also works if I change it to

if (obj[prop] {)

I don't understand why the second one works; doesn't obj[prop] just return the value of the property?

gridproquo
  • 129
  • 10
  • 3
    If property is present and not undefined it get implicitly converted to true when used in boolean context – Vinay Dec 10 '16 at 06:17
  • You can refer [When to use .hasOwnProperty](http://stackoverflow.com/questions/32422867/when-do-i-need-to-use-hasownproperty). Also `obj[prop]` will return a value. If this value is not `undefined` or `null` or `0` or `false`, value is true by default. For more info, refer [What values are evaluated to true and false without strict comparasion?](http://stackoverflow.com/questions/9417201/what-values-are-evaluated-to-true-and-false-without-strict-comparasion) – Rajesh Dec 10 '16 at 06:41
  • @Novice It doesn't get "implicitly converted to `true` when used in boolean context". It is "evaluated as truthy in a conditional context", which is a different thing. –  Dec 10 '16 at 07:32
  • @Rajesh No, it is not the case that "value is true by default"; it is the case that "value is **truthy**". Also, you omitted the empty string. –  Dec 10 '16 at 07:33
  • @torazaburo Thanks for pointing it out. Also then I meant `default true`, i meant `truthy`. I guess poor choice of words. Will keep it in mind. Thanks. – Rajesh Dec 10 '16 at 07:37
  • everyone forgets about poor old NaN... – dandavis Dec 10 '16 at 08:50

0 Answers0