Type and range checks
Validate data at the boundary
Lesson 17 of 20 · 12 min · Module 6: Design, validate & debug
A value can be present but unusable. Define an input contract before performing calculations or assuming a particular object shape.
Start this lesson →Free. No installation: you write and run the code in your browser, and it is checked automatically.
By the end, you’ll be able to…
- Check shape before reading properties
- Distinguish validation from coercion
The idea
Check the outer shape first, then individual properties. Number.isFinite rejects NaN, Infinity, and numeric-looking strings. A trimmed string can reveal an otherwise invisible empty title.
console.log(Number.isFinite(12));
console.log(Number.isFinite("12"));
01Start with the widest uncertainty
typeof null is object in JavaScript, so an object check alone is not enough. Arrays are objects too; explicitly reject them when your contract expects a record.
02Validate before transforming
Only call trim after proving the title is a string. A missing or numeric title cannot safely use that string method.
03Make invalid input visible
Returning null provides one consistent failure result. Callers can check for it before treating the returned value as a valid session.
Your turn
normalizeSession(value). Accept a non-array object with a nonempty string title and a finite numeric minutes value greater than zero. Return a new {title, minutes} with the title trimmed; return null for invalid input.What the checks look for
- Returns a clean record
- Rejects invalid outer shapes
- Rejects empty titles and nonfinite durations
- Does not change the caller’s title
Take this with you
Validate once at a boundary, then pass a clearer shape into the rest of the program.
Go a little further
Extend the contract with an optional level chosen from beginner, intermediate, and advanced.