1

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.

user2473015
  • 1,392
  • 3
  • 22
  • 47

1 Answers1

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).

Ray Toal
  • 86,166
  • 18
  • 182
  • 232