0

I check for a property on an object but it returns undefined even though it is there. I assume I am testing in the wrong way?

I run this

console.log(self.modules[moduleId]);

and it outputs this:

Object

    composed: Array[2]

    prototypes: Array[2]

    slideshow: Slideshow

        cardFront: false

        currentSlide: 2

(So "slideshow" is an object, an instance of my class "Slideshow".)

I step in one step further to do this:

console.log(self.modules[moduleId].slideshow);

And it returns undefined.

My if-statement looks like this, although above is probably enough to get my issue.

if ( typeof( self.modules[moduleId].slideshow == 'undefined' ) ) {
14
  • 4
    Can you post a jsfiddle of your code? Commented Feb 4, 2014 at 21:54
  • 3
    If self.modules[moduleId] really is the object structure you quote, then obviously self.modules[moduleId].slideshow isn't undefined. So something's got lost in the formation of the question. Commented Feb 4, 2014 at 21:59
  • 2
    @digitalextremist that is incorrect - in your case, 'undefined' should not be quoted. Commented Feb 4, 2014 at 21:59
  • 1
    YOur brackets are wrong. if(typeof self.modules[moduleId].slideshow == 'undefined') would be correct (or if((typeof self.modules[moduleId].slideshow) == 'undefined'), but those are unnecessary). ANd, another thing: keep in midn that this only checks .slideshow. If modules[moduleId] doesn't exist in the first palce, you still get an error - so check that one first. Commented Feb 4, 2014 at 22:00
  • 2
    @aduch: It's not that the () create "ambiguity," it's that they make the expression wrong. == will always return a boolean. typeof will always be "boolean" with the () as in the OP's question, because the () make typeof apply to the expression rather than to self.modules[moduleId]. Commented Feb 4, 2014 at 22:04

1 Answer 1

2

The parantheses in your if-clause are wrong. With the parentheses you have, typeof operates on the value of the comparison expression, which is always a boolean.

Instead, use either

if (typeof self.modules[moduleId].slideshow == 'undefined')

...which will be true if slideshow doesn't exist at all on the object, or if it exists but has the value undefined.

Or make use of the inoperator

if ('slideshow' in self.modules[moduleId])

...which will be true if the object or its prototype has the property, regardless of its value.

Or use hasOwnProperty:

if (self.modules[moduleId].hasOwnProperty('slideshow'))

...which will be true if the object itself (not its prototype) has the property, regardless of its value.

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

1 Comment

Nice additions, @T.J.Crowder, appreciate it!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.