traditional
traditional

Reputation: 983

Is there a better way to check existence of object's property?

I have thisif condition.

if object.fruit and object.fruit isnt 'mango'

How can ? be utilised here? I tried using if object.fruit? isnt 'mango', but condition passes when object is empty object.

Upvotes: 1

Views: 60

Answers (1)

VLS
VLS

Reputation: 2346

You want to check for three things:

  1. Ensure the object exists: object?
  2. Ensure the object has the key you're looking for: key of object
  3. Test for the key value: object.key isnt 'mango'

All together that's:

if object? and "fruit" of object and object.fruit isnt 'mango'

You can play around with the values of obj in this demo: http://codepen.io/anon/pen/VLOMpm

Upvotes: 3

Related Questions