13

I have this function:

      function ddd(object) {
        if (object.id !== null) {
            //do something...
        } 
    }

But I get this error:

Cannot read property 'id' of null

How can I check if object has property and to check the property value??

deltree
  • 3,756
  • 1
  • 30
  • 51
Michael
  • 13,950
  • 57
  • 145
  • 288
  • 1
    You can use `if(object.property)` or `if(object.hasOwnProperty('property'))` – Jeremy Jackson Sep 01 '16 at 15:10
  • 2
    Try `if (typeof(object.id) !== 'undefined')` – David R Sep 01 '16 at 15:11
  • use `obj.hasOwnProperty("id")` – vkstack Sep 01 '16 at 15:11
  • Your error doesn't have anything to do with `id` - your `object` itself is null. `if (object && object.id !== null)` would solve that. – Joe Enos Sep 01 '16 at 15:12
  • By the way, I would avoid naming a variable `object` - it seems like it's ok in javascript, but other languages have `object` as a keyword, and `Object` is reserved, so I'd personally stick with `obj` or another alternative, if you don't have a more meaningful name. – Joe Enos Sep 01 '16 at 15:14
  • I actually don't think this is a duplicate. you asked "and to check the property value?" to check the value, try "[optional chaining](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining)" `if (obj?.id !== null) {...}` – bristweb Jun 30 '21 at 22:17

1 Answers1

24

hasOwnProperty is the method you're looking for

if (object.hasOwnProperty('id')) {
    // do stuff
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty

As an alternative, you can do something like:

if (typeof object.id !== 'undefined') {
    // note that the variable is defined, but could still be 'null'
}

In this particular case, the error you're seeing suggests that object is null, not id so be wary of that scenario.

For testing awkward deeply nested properties of various things like this, I use brototype.

deltree
  • 3,756
  • 1
  • 30
  • 51
  • My linter says this is deprecated. Is there another way to handle this? Using React. – wuno Oct 25 '17 at 14:46
  • it is faster to just do `if (object.id) { // do stuff }` but this has issues if `object.id` is `false` or `0` – deltree Oct 25 '17 at 16:39