X O X O - 7 months ago 11
Javascript Question

Is there way to check if an object exists and has a child in a single line?

Is there a way to check if

req.user.premium
is true without having to check if
req.user
exists or is there a way to simplify this into a single line?

I've tried just checking
req.user.premium
but if
req.user
is empty then it throws an error because
req.user
is
undefined
, the same goes for
req.user && req.user.premium
.

if(req.user){
if(req.user.premium){
console.log('Is premium');
}
}

Answer

One line, (assuming you still console.log an empty val):

console.log((req.user && req.user.premium) ? 'Is premium' : '');

OR 2 lines (1 statement line):

if(req.user && req.user.premium)
    console.log("is premium");

EDIT:

Assuming your req object is undefined... do this:

One line, (assuming you still console.log an empty val):

console.log((req && req.user && req.user.premium) ? 'Is premium' : '');

OR 2 lines (1 statement line):

if(req && req.user && req.user.premium)
    console.log("is premium");

If the first condition (req) is undefined, the second and third conditions will not be evaluated - AKA: Short-Circutiing)

Comments