I use present or not as flag then perform relevant action. Like in my case I do something with stock or grade or both. Guess what is the problem?
stock = parseInt(req.body.stock),
grade = parseInt(req.body.grade),
var update = {};
if(stock){
update = {'data.$.stock':stock}
}
if(grade){
update = {'data.$.grade':grade}
}
if(stock && grade){
update = {
'data.$.grade':grade,
'data.$.stock':stock
}
}
There will be a bug if stock 0 is allowed in this case. So if inventory is zero, the bug will occur. Because it doesn't pass if(stock){}, hmm how to resolve this?
I don't want to write if stock is not undefined && stock is not null, that's too long.
You could simplify the code by assigning to a property, instead of assigning a whole object.
stock = parseInt(req.body.stock, 10), // use radix as well
grade = parseInt(req.body.grade, 10),
var update = {};
if (stock >= 0) {
update['data.$.stock'] = stock; // set property
}
if (grade >= 0) {
update['data.$.grade'] = grade; // set property
}
// skip part for assigning both
You could use isNaN(). Like
if (!isNaN(stock))
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/isNaN
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With