Before this lesson

Know how to open the browser Console. This lesson starts with values and types; asynchronous programming is not required.

What you will be able to do

Distinguish value types from variable bindings and explain why adding form values can concatenate text.

Understand the mechanism

Values include strings, numbers, booleans, undefined, null, BigInt, Symbol and objects. typeof is a useful first check, not a complete validator: typeof null is object; use Array.isArray for arrays. Types belong to values, while variables hold values or object references.

const prevents rebinding; it does not freeze an object. Use let when reassignment is intentional. Prefer const to make state changes easier to locate. Two variables referencing one object observe the same property mutations. Object spread copies only one level.

input.value is a string. Check trimmed emptiness before Number conversion, then use Number.isFinite to reject non-finite numbers. Number of an empty string is zero, so a NaN check alone cannot enforce required input. Strict equality avoids loose conversion; money calculations commonly use integer minor units.

Runnable example

const raw = " 12.5 ";
const value = Number(raw);
const valid = raw.trim() !== "" && Number.isFinite(value);
console.log(typeof raw, typeof value, valid);
console.log("12" + 3, Number("12") + 3);
const first = { done: false };
const second = first;
second.done = true;
console.log(first.done);

Trace and verify

Predict before running: string number true; the string 123 versus the number 15; finally true. Try whitespace, abc and Infinity and verify valid is false. Re-run the entire example after changing raw.

Common mistakes and boundaries

Do not use if(value) to validate numbers: zero is valid but falsy. Floating-point representation introduces rounding; 0.1 + 0.2 is not strictly 0.3. Formatting decimals does not change internal precision.

Practice challenge

Write parseScore: return null for empty, nonnumeric or out-of-range input; otherwise return a number. Test zero, 100, whitespace and 101.

Reference solution and reasoning

Reject emptiness first, then check finiteness and bounds. Represent failure with null and compare explicitly so zero remains valid.

function parseScore(raw) {
  if (raw.trim() === "") return null;
  const n = Number(raw);
  return Number.isFinite(n) && n >= 0 && n <= 100 ? n : null;
}

Further reading