how to check if variable is blank or undefined in node js [duplicate]

倾然丶 夕夏残阳落幕 提交于 2019-12-13 09:20:44

问题


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


回答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 
}



回答2:


You can do it like this

if(typeof variable === 'undefined'){
//Variable isn't defined
}



回答3:


it is working

if(req.body.gradeDescription == '' || req.body.gradeDescription === undefined)


来源:https://stackoverflow.com/questions/34878755/how-to-check-if-variable-is-blank-or-undefined-in-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!