Viswanathan
Viswanathan

Reputation: 1

How to give a null check in both if and else statement

if (!away) {
   return self.data.a1;
}
else {
   return self.data.a2;
}

I am getting undefined in both if and else statement for self.data

Upvotes: 0

Views: 102

Answers (5)

bloC
bloC

Reputation: 526

The best way to check is to do it like:

if(typeof(self.data.a1) != "undefined"){ /* do whatever shall be done in this case */ }

I hope this helps.

Upvotes: 0

Martin
Martin

Reputation: 16292

This is what you want

If (!away && self && self.data) {

Or just wrap your in a try/catch and handle the exception locally.

Upvotes: 1

artm
artm

Reputation: 8584

You could write the if condition on one line, try it in your console:

var self = {'data': { 'a1': 'a1' } };

console.log((!away && self.data) && (self.data.a1 || self.data.a2))

self.data.a2 = 'a2';
self.data.a1 = null;

console.log((!away && self.data) && (self.data.a1 || self.data.a2))

logs a1 and a2.

Upvotes: 0

AwokeKnowing
AwokeKnowing

Reputation: 8206

here's how you can check if they're defined

if (!away) {
    if(typeof self !== 'undefined' && 
       typeof self.data !== 'undefined' && 
       typeof self.data.a1 !== 'undefined')
        return self.data.a1;
} else {
    if(typeof self !== 'undefined' && 
       typeof self.data !== 'undefined' && 
       typeof self.data.a2 !== 'undefined')
        return self.data.a2;
}

Upvotes: 0

LexJacobs
LexJacobs

Reputation: 2533

your return statement only works if it is contained within a function scope, such as:

var away = false;
var self = {
    data: {
        a1: 'hi',
        a2: 'ho'
    }
};

var a = function(){
  console.log(self, self.data);
    if (!away) {
        return self.data.a1;
    } else {
        return self.data.a2;
    }
};

console.log(a()); // returns 'hi

But if that was obvious to you and that's not the problem you're having, then yes, perhaps a console.log of self.data will help diagnose the problem.

Upvotes: 0

Related Questions