0

I was trying to check if an input field with the type of number is empty, and I already found how to do it but I can't understand why

I found an answer which taught me how to do it, but not why, and I really want to understand how it works in the background

I know that if I use the length method it won't work since it is used to look for a string, but if I leave it empty and click on the button, what will be sent, a null value, an undefined or anything else?

here is the code I used to check:

if (!value) {
  //do work here
}
kyun
  • 9,710
  • 9
  • 31
  • 66
Eduardo
  • 407
  • 1
  • 4
  • 12
  • Integers are 'truthy' in JavaScript, so you're essentially checking `if ([not] true)` when the input is a positive integer(s), and `if ([not] false)` when the value is empty. Thus your check will determine whether a number is passed in or not. The actual *restriction* of a number type happens in `input type="number"` on the HTML side. – Obsidian Age Aug 26 '19 at 00:49
  • Just a point of clarification: *non-zero* integers, or non-zero numbers of any sort, are truthy, but 0 is falsy (and so is `NaN`). – kshetline Aug 26 '19 at 00:55
  • so when i leave the field empty, it sends an undefined value which is considered as falsy? @ObsidianAge – Eduardo Aug 26 '19 at 00:57
  • Actually, even when you say that an input is `type="number"`, you're getting numbers back in string form. So you'll have an empty string (`''`) when the field is empty. It wouldn't hurt to test for `null` and `undefined` too, just in case -- those values can be set programmatically to make an input field blank. – kshetline Aug 26 '19 at 01:02
  • Oh, and once you're sure it isn't `null` or `undefined`, `value.length === 0` is perfectly fine to test too, since it will be a string. – kshetline Aug 26 '19 at 01:04

0 Answers0