How to check if an javascript boolean element is present

Viewed 4741

At this point, I check if elements in an node.js object exist and get the value by doing:

if(req.body.name) item.name = req.body.name;

However, if I want to do the same for a boolean element, it is not working. If the passed boolean is true, no problem, but if the passed boolean is false, the if statement fails, however, I need the value of it:

if(req.body.active) item.active = req.body.active; // works only if true

Is there a better way to check if an element in an object exists and to validate the boolean value of it?

5 Answers

For me the below code worked really well:

if (req.body && typeof req.body.name === 'boolean')

It will work for all the cases where name is undefined or name is boolean or name is not boolean or body does not exists. It handles all the cases.

Related