14

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??

6
  • 1
    You can use if(object.property) or if(object.hasOwnProperty('property')) Commented Sep 1, 2016 at 15:10
  • 2
    Try if (typeof(object.id) !== 'undefined') Commented Sep 1, 2016 at 15:11
  • use obj.hasOwnProperty("id") Commented Sep 1, 2016 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. Commented Sep 1, 2016 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. Commented Sep 1, 2016 at 15:14

1 Answer 1

25

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.

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

2 Comments

My linter says this is deprecated. Is there another way to handle this? Using React.
it is faster to just do if (object.id) { // do stuff } but this has issues if object.id is false or 0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.