how to check if variable is blank or undefined in node js
29,350
Solution 1
Because an undefined variable is "falsey", you can simple do
if (body.req.gradeName) {
// do normal stuff
} else {
// do error stuff
}
Or if you don't need to do anything if it is defined, then you can do
if (!(body.req.gradeName)) {
// do error stuff
}
Solution 2
You can do it like this
if(typeof variable === 'undefined'){
//Variable isn't defined
}
Author by
Ashutosh Jha
Updated on January 20, 2020Comments
-
Ashutosh Jha over 4 years
I want to check my data is blank or undefined but my if block execute even my data is not blank ...
Code is :
router.post('/addNewGrade',function(req , res){ var errorMsg = []; console.log(req.body.gradeName) if(req.body.gradeName == '' || req.body.gradeName === undefined){ errorMsg.push("please enter grade name"); } if(req.body.gradeDescription == '' || req.body.gradeDescription === undefined){ errorMsg.push("please enter description about your grade"); } if(errorMsg !=''){ res.send({errorMessage :errorMsg}); return; } });
what is the best way to check variable is undefined or not