Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 3

Handling Valid and Invalid Inputs with Conditional Logic

Recommended resources

Hello! Last time, you wrote functions with typed parameters and return values. You also saw that calculateCharge(25, -3) passes TypeScript’s type check even though a negative membership term makes no sense. Today you’ll put a decision inside a function: accept inputs that meet a stated rule, and return a clear result when they do not.

This is the same small-scale reasoning you’ll use when writing backend handlers. For now, we’ll keep the inputs in a TypeScript program so you can concentrate on writing and tracing the conditional logic yourself.


One condition, two possible results

An if statement evaluates a condition. If it is true, its block runs; otherwise, an optional else block runs. Watch the basic behavior first, then notice why the order of checks matters when there is more than one.

If statements in JavaScript are easy 🤔

Watch “If statements in JavaScript are easy” by Bro Code for a visual introduction to branches and a useful warning about checking conditions in the wrong order.

Watch two branches to see how if and else select different blocks. Then skip to check order: focus on why a broad condition can prevent a later, more specific condition from running. The examples print messages; our functions will return them.

Suppose a membership term is valid only when it is a whole number from 1 through 12, including both endpoints. Write that rule before writing the function. It gives you a concrete condition to implement and tells you which boundary values to inspect.

function getTermMessage(months: number): string {
  if (Number.isInteger(months) && months >= 1 && months <= 12) {
    return "Term accepted";
  } else {
    return "Invalid term";
  }
}

console.log(getTermMessage(3));   // Term accepted
console.log(getTermMessage(0));   // Invalid term
console.log(getTermMessage(12));  // Term accepted
console.log(getTermMessage(1.5)); // Invalid term

Number.isInteger(months) checks the whole-number requirement. Each comparison checks one boundary. The && operator means all three checks must pass. If they do, the first return ends the function with "Term accepted"; otherwise, the else branch returns "Invalid term".

The number annotation did not enforce the rule. Zero, 13, and 1.5 are all numbers. The conditional handles their meaning for this function.



Turn a rule into a precise condition

The comparisons you need most often are === for strict equality, !== for inequality, and <, <=, >, >= for numeric boundaries. Combine complete comparisons with && when every requirement must hold, or || when any one of several conditions is enough.

Read MDN’s concise reference before we add another invalid-input case.

Making decisions in your code — conditionals - MDN Web Docs

Read MDN Web Docs’ “Making decisions in your code — conditionals” to connect comparison and logical operators to the rules you put in an if statement.

In the “if...else statements” section, find “A note on comparison operators.” Read the comparisons, paying attention to inclusive versus exclusive boundaries. Then, under “Logical operators: AND, OR and NOT,” read the logical operators. Focus especially on why each side of || needs its own complete test.

The choice between && and || depends on how you phrase the rule. To accept a term, it must be an integer and at least 1 and at most 12. To reject it, any one failure is sufficient: it is not an integer, or it is below 1, or it is above 12.

if (!Number.isInteger(months) || months < 1 || months > 12) {
  return "Invalid term";
}

The ! negates the result of Number.isInteger. This rejection check expresses the same rule as the earlier acceptance check, but it puts the invalid case first. Be careful not to write months < 1 || > 12: both sides of || need a complete expression, such as months > 12.

Boundary values make a rule testable. For a valid range of 1 through 12, check 1 and 12 as well as values just outside them. If you accidentally write months < 12, a perfectly valid 12-month term will be rejected.



Reject invalid inputs before calculating

Let’s extend the previous lesson’s charge calculation. The intended inputs are a finite monthly price greater than zero and a whole-number term from 1 through 12 months. We’ll return a string so that the function can give either a total or an explanation of which input failed.

MDN’s input-validation guidance distinguishes between receiving the expected kind of value and checking whether that value is acceptable. Read its small range-check examples with that distinction in mind.

Input validation - Security | MDN

Read MDN Web Docs’ “Input validation” for the reason to state allowed values explicitly, rather than assuming that inputs are safe because they look plausible.

Under “Validation guidelines” and “Implement validation as an allowlist,” read range and validation. Compare the two range-check functions, then find “Syntactic and semantic validation” and distinguish the two checks. In the continuation of that subsection and “When to validate,” read validation timing; focus on why a server cannot rely on a browser to reject bad input. You can skip the discussion of regular-expression libraries for this lesson.

Here is the function. Read each if as a gate: if an input fails, return immediately. The calculation is reached only after both inputs pass.

function getChargeMessage(monthlyPrice: number, months: number): string {
  if (!Number.isFinite(monthlyPrice) || monthlyPrice <= 0) {
    return "Invalid monthly price";
  }

  if (!Number.isInteger(months) || months < 1 || months > 12) {
    return "Invalid number of months";
  }

  const total = monthlyPrice * months;
  return "Total charge: " + total;
}

console.log(getChargeMessage(25, 3));   // Total charge: 75
console.log(getChargeMessage(25, 0));   // Invalid number of months
console.log(getChargeMessage(-5, 3));   // Invalid monthly price
console.log(getChargeMessage(25, 1.5)); // Invalid number of months

Number.isFinite rejects values such as Infinity and NaN that JavaScript still represents as numbers. The second check rejects fractional or out-of-range terms. Notice that this version does not need else: once an invalid branch returns, that call cannot continue to the calculation.

Order is deliberate. If both inputs are invalid, the function reports the monthly price first because that check runs first. In a short function, this pattern keeps the valid calculation easy to see.

This is a teaching example, not a production payment calculation. Real payment code needs an explicit approach to currency units and rounding. The conditional principle remains the same: do not perform the main action until its input requirements have been checked.



Run and trace the branches

Put the complete getChargeMessage example in src/main.ts. As in the previous lesson, run npm run build, then npm start. Before each run, look at a call and identify the first condition that will be true. For getChargeMessage(25, 0), the price check is false, but the months check is true, so the function returns the months error without multiplying.

When you’re comfortable tracing the supplied calls, hide the function body and retype it from these three requirements: reject an invalid price, reject an invalid term, and otherwise return the calculated total. Use the compiler and your observed output to check your work rather than asking a code generator to fill in the branches. If a build fails, fix it before running npm start; otherwise you may be running older JavaScript left in dist.

One limit is worth keeping clear. The parameters here are annotated as number, so TypeScript checks ordinary calls in your TypeScript source. That annotation alone does not prove that a value arriving in an HTTP request is a number: TypeScript types are absent at runtime. Later, you’ll validate incoming data’s actual shape before passing it to functions like this one.



Conclusion

A reliable small function starts with an explicit rule, checks its boundaries, returns on invalid inputs, and performs its main work only when those checks pass. if and else select branches; &&, ||, and ! let you express the rule precisely; and return stops the current function call. Type annotations help describe inputs, but they do not replace runtime validation.

You’ve now completed the first module’s path from stack responsibilities to writing a typed program with meaningful decisions. Next, you’ll begin representing application records with TypeScript types and working with their fields.