Validate the input

INPUT · Slides

Block empty input

01 / 05

What happens when you press Add with nothing?

Try pressing Add right now without typing anything. A blank row appears.

It does not crash, but it looks wrong. Stopping this kind of thing is called input validation, and every real-world app has it.

02 / 05

Use trim to strip invisible whitespace

Typing just spaces is equally wrong. trim() returns the string with whitespace stripped from both ends.

" " becomes "" after trimming. "buy milk" stays the same. Checking after trim() is the most reliable way to tell if something was actually typed.

"  ".trim()       // "" (only whitespace)"buy milk".trim() // "buy milk"

03 / 05

Return early when it is empty

Once you know it is empty, leave before anything else runs. That is what return does.

return inside an if skips everything below it. Rejecting bad cases early is called a "guard" in the real world.

if (input.value.trim() === "") {  return}

04 / 05

trim does not change the original value

Here is the catch: trim() only returns a new string — it does not change input.value itself.

So check with input.value.trim(), and use the trimmed value when you actually add it to the list too. A common mistake is trimming only for the check and then adding the untrimmed original, which leaves stray spaces registered on the item.

const raw = "  buy milk  "console.log(raw)            // "  buy milk  " (unchanged)console.log(raw.trim())     // "buy milk" (whitespace gone)

05 / 05

A guard often reads better than if / else

You could write the same thing with if and else, but a guard is often cleaner. With else, the code you actually care about ends up indented one level deeper.

A guard reads as "clear the bad cases first, and everything left over is what you actually want to do." The longer the real logic gets, the more that difference matters.

// with else (the real logic sits one level deeper)if (input.value.trim() !== "") {  addItem(input.value.trim())}// with a guard (the real logic stays shallow)if (input.value.trim() === "") {  return}addItem(input.value.trim())