← React / TypeScript

React / TypeScript · 03 / 18

Operators, comparisons and if

Choose between workflows based on a condition.

  • Small
  • Basics
  • 15 min

Prerequisites: Variables and data types in JavaScript

A condition is an expression whose result selects a branch. We check a cost amount. +, -, * and / perform arithmetic. === compares without automatically converting different types. if executes a block when its condition matches. else handles the other case.

Example files

01Compare strictly

0 === "0" is false because a number and text have different types. == would convert here. Forms often provide text. We want conversion to be explicit rather than hidden inside a comparison.

conditions.mjs · javascriptOpen file
const costCents = 12990;
if (costCents < 0) {
  console.log('Invalid cost');
} else if (costCents === 0) {
  console.log('Free repair');
} else {
  console.log('Paid repair');
}

Run / check

node conditions.mjs

02Express the domain rule

A negative amount is invalid in this example. 0 means free. All positive amounts are chargeable. Ordering prevents a broad case from swallowing a more specific one.

03Combine conditions

&& requires two true conditions. || accepts one true condition. ! reverses a boolean value. Test costCents >= 0 && costCents <= 50000 to express an allowed range.

Expected result

With 12990: Paid repair

Your exercise

Change the value to -1, 0 and "0" in turn. Explain each branch.

Show the solution and explanation

-1 is invalid and 0 is free. Text "0" does not match numeric 0 with === and reaches the final branch. This shows why data needs a reliable type before domain validation.

Project context and sources

The example is simplified for learning. The linked source version shows its use in the project and the checks applied there.