Code Lab is in development. New lessons and improvements are on the way. Progress can be deleted.
Loading…
Code Lab is in development. New lessons and improvements are on the way. Progress can be deleted.
Loading…
Code Lab is in development. New lessons and improvements are on the way. Progress can be deleted.
JAVASCRIPT FORMS / CHAPTER 05 / Learn / LESSON 05
Theory. Field data is raw: " 40 " has spaces, "" is empty, "0" is a real zero. Three different cases — and the most common bug is mixing them up.
Normalize text: const t = el.value.trim(). Then: if t === "" — the value is missing (show "empty"). Otherwise const n = Number(t) — a real number, and 0 is perfectly valid.
Traps: - Number("") is 0 — an empty field looks like zero! - if (!t) works for "", but if (!n) also rejects a real 0. - Number("abc") is NaN — check with Number.isNaN(n).
Small example:
function describe(el) { const t = el.value.trim(); if (t === "") return "empty"; return String(Number(t)); }
Common mistake: empty = 0; 0 = empty; forgotten trim.
<input id="a" type="text"><input id="b" type="text"><input id="c" type="text"><button id="go" type="button">Check</button><p id="out-a"></p><p id="out-b"></p><p id="out-c"></p>An empty string and 0 are different cases; Number("") is 0 — so check for empty first.
Press Run — HTML loads in a sandbox iframe; Stop removes the iframe (also kills infinite loops).
›