3

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

3
  • You could check if errorMsg.length > 0 show the error? Commented Jan 19, 2016 at 14:02
  • Please log the values of req.body.gradeName etc. to confirm their value. Commented Jan 19, 2016 at 15:15
  • What does "blank" mean? Commented Jan 20, 2016 at 19:55

3 Answers 3

19

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 
}
Sign up to request clarification or add additional context in comments.

5 Comments

Sure, but how does this explain the behavior reported by the OP?
Apologies! I missed that. I agree with you torazaburo, I would like to see what the console.log value of gradeName is.
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.
This will go to the error branch for several "normal" values
If body.req.gradeName cames with '0' will do the 'error stuff', sometimes is not the expectd behavior
13

You can do it like this

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

Comments

-2

it is working

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

1 Comment

that seems to be the exact same thing as your starting post...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.