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.
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.
-
2
if (stock == null)
will be true whenstock
is eithernull
orundefined
. – Pointy Commented Jan 2, 2017 at 17:20 -
1
stock
will never even beundefined
ornull
it will either be a number orNaN
. – VLAZ Commented Jan 2, 2017 at 17:20 -
2
"I don't want to write if stock is not
undefined
&& stock is notnull
, that's too long." That's an odd reason, considering you were willing to write 20x that in your question here. – ceejayoz Commented Jan 2, 2017 at 17:20 -
1
Too long? Too bad. Either stop using
undefined
the way you're using it, or deal with the fallout :) – Luaan Commented Jan 2, 2017 at 17:21
3 Answers
Reset to default 7You 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/en/docs/Web/JavaScript/Reference/Global_Objects/isNaN
Simply pare stock being greater than or equal to 0:
if (stock >= 0)