Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

allow zero (0) in if checking javascript

Tags:

javascript

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.

like image 809
Thian Kian Phin Avatar asked Dec 03 '25 13:12

Thian Kian Phin


2 Answers

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
like image 95
Nina Scholz Avatar answered Dec 05 '25 02:12

Nina Scholz


You could use isNaN(). Like

if (!isNaN(stock))

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/isNaN

like image 26
Shreyash S Sarnayak Avatar answered Dec 05 '25 02:12

Shreyash S Sarnayak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!