Hello, my name is: Amy

Making Sure an Object has a Property

In the web app that I'm currently working on I seem to be running into a situation that is just something that I don't fully understand yet. I am working through that understanding by writing about it. Bear with me.

It's all about making sure things exist before you try and use them as to avoid the dreaded Uncaught TypeError: Cannot read property 'blank' of undefined. So, in my code at some points I will need to check if a bit of data has a specific property, before I can use bits of its data.

This error was popping up to me for a few reasons:

  • it took a bit for my data to return from the promise (?) before it was ready to use.
  • all the iterations of data didn't have all the same properties, but I needed logic around them
var myData = {
    slide : [
        {
            words    : 'la di da',
            audio : 'sound.mp3',
        },
        {
            words    : 'di de da',
            sub : {
                _type : 'special',
                words : {
                    text  : 'wrd',
                    audio : true
                }
        },
    ],
};

I found that I couldn't go outright and ask if (slide.sub._type == 'special') because I'd get 'The Error' on slides that didn't have the property sub.

My plan became to just check first and ask if sub was there before asking if (sub._type == 'special'). I started out by doing this:

if  ( slide.sub && slide.sub._type == 'special') {
    //now do things
}

My logic is that my checking if (slide.sub), if the property existed it would be true and if not false.

Double Bang !!

I could use if (!!slide.sub) to force that to a true/false, but seeing as how there are such things as truthy and falsy I'm not so sure I understand it enough to rely on it, which I might have actually been doing already in the case above by just using if (slide.sub)

Checking If Undefined

After seeing that console.log(slide.sub) output undefined I then moved to:

if  ( slide.sub != undefined && slide.sub._type == 'special') {
    //now do things
}

But I'm not really crazy about this because if I wanted to check something futher deep then that things start getting pretty ugly:

if  ( slide.sub != undefined && slide.sub.words != undefined 
&& slide.sub.words.audio == true ) {
    //now do things
}

.hasOwnProperty()

After some light research I came across .hasOwnProperty().

The hasOwnProperty() method returns a boolean indicating whether the object has the specified property.

I've been using that a little, but I still can't go out and say if (myData.slide[0].sub.hasOwnProperty('_type')) because I run into the same problem of Uncaught TypeError: Cannot read property 'hasOwnProperty' of undefined because on that slide, sub isn't present.

Sigh.

Comments