1

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

bwegs
  • 3,711
  • 2
  • 27
  • 31
Ashutosh Jha
  • 166
  • 1
  • 2
  • 10

3 Answers3

20

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 
}
gradorade
  • 294
  • 1
  • 9
  • Sure, but how does this explain the behavior reported by the OP? –  Jan 19 '16 at 15:16
  • Apologies! I missed that. I agree with you torazaburo, I would like to see what the console.log value of gradeName is. – gradorade Jan 19 '16 at 15:24
  • 1
    CAREFUL with this, if body.req.gradeName is false ("false" or false), you're not in an error situation, false can be a value too. – Frank Feb 17 '20 at 15:53
4

You can do it like this

if(typeof variable === 'undefined'){
//Variable isn't defined
}
Tewdyn
  • 627
  • 3
  • 15
-2

it is working

if(req.body.gradeDescription == '' || req.body.gradeDescription === undefined)
Ashutosh Jha
  • 166
  • 1
  • 2
  • 10