Firstly, it depends on the library you are using, maybe there are utilities for some libraries, I suppose you are using express-session .
It is just OK:
if(req.session.user){}
They are useless:
if(typeof req.session.user !== "undefined"){} if(typeof req.session.user !== "undefined" || req.session.user === true){}
Reason : req.session is an object, just like regular objects:
var obj = { name : "adam" }
If you try to get obj.age that it does not exist and is not defined, the getter function of the object, first of all, check if it exists or not, if it is not, it will not lead to a fatal error , and instead it assigns it the property value is undefined .
This is cool, so obj.age get undefined (JS has undefined as a value type), moreover undefined is a fake value (when you force it to boolean, it becomes false, so it is false), which means you can just check it in conditional statements as follows: if(obj.age){}
source share