0

I've knocked up a simple calculator in vanilla JS. However when the user enters a 0 the calculation does nothing. I'd expect it to take 0 for example x it by 10 and give the answer 10. As an example. I'm guessing this line is stopping 0. Any ideas?

const isValid = field => (field && field !== '' && !isNaN(field));
ajcodes
  • 35
  • 4
  • `0` is falsey. `0 == false` equals true. Read more here: https://developer.mozilla.org/en-US/docs/Glossary/Falsy – Dominik May 31 '20 at 22:49
  • Does this answer your question? [Why do all numbers except 0 pass an if statement in JavaScript?](https://stackoverflow.com/questions/33960456/why-do-all-numbers-except-0-pass-an-if-statement-in-javascript) – Ivar May 31 '20 at 22:55

2 Answers2

1

try this out

const isValid = field => (typeof field !== 'undefined' && field !== '' && !isNaN(field));
fazlu
  • 856
  • 5
  • 10
  • 1
    Please don't use `typeof foo !== "undefined"`. That practice is largely abandoned because it can cause more problems than it supposedly solves. Just do`foo !== undefined` or if you want to test `null` too, then `foo != undefined`. –  May 31 '20 at 23:13
1
const isValid = field => (field === 0 || (!!field && !isNaN(field)));

Since 0 is falsey, you can handle it separately. true || false will return true.

!!field takes care of undefined, '', null, 0, etc. Basically it handles all falsey values. So you don't need to check for '' separately. Since !'' is true, so !!'' is false.

Rohan Mukherjee
  • 280
  • 2
  • 7