Dillinger
Dillinger

Reputation: 1903

How to avoid undefined variable with if condition?

In my code I've a method that check if a select option is clicked or not, like this:

$("#selected-service").click(function ()

now all working fine, but inside of this method I valorize this variable:

var appointment = BackendCalendar.lastFocusedEventData.data;

in some case this variable is returned undefined, and this is normal 'cause this variable rapresent if the user is in the edit mode or adding mode of an appointment. In the first case the variable was returned undefined as well. Anyway, I perform this condition:

try
{
   var appointment = BackendCalendar.lastFocusedEventData.data;

   if (appointment != 'undefined')
   {
      //do this...
   }
   else 
   {
      //do this...
   }
}
catch(Ex){  console.log("Error=>" , Ex);    }

but the problem is that the else condition is never fire 'cause the code go in the catch exception. Now, the question is simple: how I can bring in the else if the variable is undefined?

POSSIBLE SOLUTION:

if(typeof(BackendCalendar.lastFocusedEventData !== 'undefined'))
{
    appointment = BackendCalendar.lastFocusedEventData.data;
}

Upvotes: 0

Views: 3633

Answers (4)

P. Janowski
P. Janowski

Reputation: 306

Try this, rather than checking content of the variable, check its type.

if(typeof appointment !== "undefined"){
//do this
} else {
//do that
}

EDIT:

This will work but remove the brackets:

if(typeof BackendCalendar.lastFocusedEventData !== 'undefined')
{
    appointment = BackendCalendar.lastFocusedEventData.data;
}

Upvotes: 1

RiccardoC
RiccardoC

Reputation: 866

I created a function to verify all the object instance

function definedVar( string, containerVar ) {
    var splitted = string.split( "." );
    var testVar = containerVar;
    for( var i = 0; i < splitted.length; i++ ) {
        var propertyName = splitted[ i ];
        if( testVar[ propertyName ] == undefined ) {
            return false;
        }
        testVar = testVar[ propertyName ];
    }
    return true;
}

See it in action HERE

Upvotes: 0

Shaun
Shaun

Reputation: 927

Clearly the problem isn't with the appointment variable, it's with the:

BackendCalendar.lastFocusedEventData

Probably being null or undefined.

If you set appointment like so:

   var lastDate = BackendCalendar.lastFocusedEventData, appointment = lastDate ? lastDate.data : undefined

It should work.

Also personally I just use

if(!appointment) {
...

Which covers both null and undefined checks (if your sure it will NEVER be zero)

Upvotes: 0

wizzardmr42
wizzardmr42

Reputation: 1644

if (typeof appointment != 'undefined') ...

Upvotes: 0

Related Questions