I try to check if session in Express 4 is exist:
if(req.session.user == undefined) {}
It gives me error:
Cannot read property
Firstly it depends on the library you are using, maybe some libraries have utilities for that, I assume you're using express-session
.
This is just Okay:
if(req.session.user){}
They are useless:
if(typeof req.session.user !== "undefined"){}
if(typeof req.session.user !== "undefined" || req.session.user === true){}
The reason: req.session
is an object, just like normal objects:
var obj = { name : "adam" }
If you try to get obj.age which it doesn't exist and defined, the getter function of the object, firstly check if it exists or not, if it's not, it wouldn't produce a fatal error and instead it assigns that property to undefined value.
That's cool, so obj.age
get's undefined ( JS has undefined
as a value type), moreover undefined
is a falsy value (when you coerce it to boolean it becomes false, so it's falsy), which means you can simply check it in conditional statements like this: if(obj.age){}