Search code examples
node.jsundefinedundefined-behavior

Cheking if variable is undefined


So I want to check if a variable is undefined in node.js. So far I work like this:

if(typeof object.data.items[1] === 'undefined')
{
    break;  
}
else
{
    console.log("Defined");         
}

But it gives me this error:

"TypeError: Cannot read property 'data' of undefined".

Any ideas on how to bypass this error while still checking if it's undefined?


Solution

  • check both object and object.data is defined first.

    if(object && object.data && typeof object.data.items[1] === 'undefined')
    {
        break;  
    }
    else
    {
        console.log("Defined");         
    }
    

    or

    if(!object || !object.data || typeof object.data.items[1] === 'undefined')
        {
            break;  
        }
        else
        {
            console.log("Defined");         
        }