2

I have used like below example to check property exists on an object.

const payload ={payment:0} if(payload && payload.payment){ console.log(payload.payment) }else{ console.log('Issue') } 

But it fails with 0 (Zero) value.

This question is about an object which has integer key and when the key value is zero most of the other answers don't work.

2
  • 1
    Have you tried it? 'payload' in payment does work. Commented Oct 6, 2018 at 20:33
  • @FlorianWeimer I found has in lodash also do this. Commented Oct 7, 2018 at 4:05

1 Answer 1

3

To see if the property payment exists in the object payload you can write

'payment' in payload 

or if you want to know if the property is directly defined in the object (as opposed to being inherited through the prototype), say

payload.hasOwnProperty('payment') 

The expression payload.payment, when the value is 0, will produce false when used as a boolean. This is because the following values will always act like false:

  • 0
  • false
  • NaN
  • undefined
  • null
  • empty strings

The technical term for these values, that act as false, is "falsy." So because 0 is falsy, whenever you write !payload.payment, this value is actually true for 0 and false for everything else. Check for the missing property using one of the two techniques above (in or hasOwnProperty).

Sign up to request clarification or add additional context in comments.

1 Comment

I found has in lodash also do this.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.