JAVASCRIPT / CHAPTER 02

Values and decisions

Beginner

Turn explicit input rules into predictable expressions.

By the end of this chapter

  • Distinguish text from numeric values
  • Choose defaults without discarding valid zeroes
  • Trace branches with strict comparisons

The idea

JavaScript values have types even though a variable does not require a type annotation. Start by separating strings, numbers, booleans, null, and undefined. A search field supplies text; arithmetic may require deliberate conversion. Use const when the binding should not change and let when reassignment is part of the algorithm. Strict equality compares without converting different types.

A default is a policy decision. The nullish operator replaces only null and undefined, while logical OR also replaces zero, false, and empty text. Write the missing-value rule before choosing an operator. In a branch, evaluate the condition first and follow only its selected path. Test a normal value, a boundary value, and an absent value to expose accidental coercion.

JavaScript example
const requested = 0;
const limit = requested ?? 10;
console.log(limit);
console.log("4" === 4);
Result
0
false

Zero remains a valid limit because it is not nullish. The string and number contain similar characters but are different types.

Try it yourself

Set requested to null, then 0, then 5. For each value, use one expression to choose a page size that defaults to 20 only when requested is missing. Print and compare the three results.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

Open JavaScript coding challenges

CHECK YOUR UNDERSTANDING

Chapter checkpoint

A count may be 0, null, or a positive number. Which expression preserves 0 and substitutes 12 for null?