smartyfy.mrindigi.com

Web Development Pro | Lesson 022 | Conditions and Explicit Decisions

Web Development Pro · Lesson 22 of 60

Module 3: JavaScript foundations

In this lesson

Prerequisites and learning outcomes

Complete lesson 21 first. This lesson builds on comparisons, boolean logic, and branches. By the end, you can write clear decision rules and avoid truthiness and coercion surprises. Plan 10–15 minutes for the core explanation and additional time for the worked practice.

Turn a policy into explicit decisions

A workshop preference is reasonable only if the event is open, the requested seat count is a positive integer, and enough seats remain. These are separate conditions. Writing them clearly is better than hiding several assumptions in a clever expression. A reader should be able to connect each branch to a real rule in the task.

This is still a local calculation, not a booking service. Even a correct client-side availability message cannot reserve inventory or prevent another person from taking the same seat. The example teaches decision logic using fixed fictional values. A real system would need an authoritative server and a transaction-safe availability check.

Compare values deliberately

Use === and !== for strict equality comparisons that do not coerce unlike types into one another. A number 2 is not strictly equal to the string '2'. Relational operators such as <, <=, >, and >= compare ordering, but mixed types can still trigger conversions. Convert and validate external inputs before treating them as quantities.

The assignment operator = is different from equality. Writing requested = 2 changes a binding; writing requested === 2 asks a question and produces a boolean. Confusing the two can alter state inside a condition and make a bug look like a valid decision. Use names and formatting that make the intended question obvious.

const isOpen = true;
const requestedSeats = 2;
const availableSeats = 3;
let message;
if (!isOpen) {
  message = 'This workshop is closed.';
} else if (!Number.isInteger(requestedSeats) || requestedSeats < 1) {
  message = 'Choose a positive whole number of seats.';
} else if (requestedSeats > availableSeats) {
  message = 'Not enough seats remain in this demo.';
} else {
  message = 'The request fits the demo availability.';
}
console.log(message);

The example prints that the request fits. Number.isInteger checks both the numeric type and integer property; it does not accept the string '2' as an integer. The order of branches determines which message wins when several conditions could apply. Here a closed event takes priority over a malformed request.

Combine conditions without losing clarity

The && operator requires both operands to be truthy for its overall truthy result; || succeeds on a truthy alternative. The ! operator negates truthiness. These operators return or use values according to JavaScript's rules, not always a newly created boolean. Inside an if condition, the final result is interpreted as truthy or falsy.

Logical operators short-circuit. If the left side of && is falsy, the right side is not evaluated. If the left side of || is truthy, the right side is not evaluated. This is useful, but avoid hiding important work in a condition merely because it is shorter. An explicit branch often communicates a business rule better.

Use parentheses when grouping makes intent clearer, even if operator precedence would already produce the same answer. “Event is open and either beginners or experienced participants are accepted” has a different grouping from “event is open and beginners are accepted, or experienced participants are accepted regardless.” Translate the sentence carefully before writing operators.

Do not confuse presence with validity

Empty strings, zero, null, undefined, and NaN are falsy. The string '0' is truthy because it is nonempty. An empty array and an empty object are also truthy. Therefore if (input) is not a complete test that a seat count is valid. It only asks about truthiness, which is a language property rather than your application's policy.

Explicit conversion also needs care. Number('') produces zero, so an empty field can be mistaken for a meaningful quantity if you convert before checking the task's requirements. Later form lessons will trim input, check emptiness, convert, and validate in a deliberate sequence. Each step answers a different question.

NaN represents a numeric result that is not a valid number in the relevant operation. It is not equal to itself, even with ===, so use Number.isNaN when that specific check is needed. For this seat-count contract, Number.isInteger already rejects NaN, fractions, strings, and infinities in one clear test.

Test the branches and their priority

A good decision test includes each outcome, not only the successful path. Try closed status, zero seats, a decimal, a string, a request above availability, and a request exactly equal to availability. The boundary equality should pass because the rule rejects only requests greater than the remaining count.

Also test overlapping failures. If the workshop is closed and requestedSeats is zero, the first branch produces the closed message. That is intentional in this example. If a product needs field correction before availability feedback, its branch order might differ. Write the desired priority as a requirement rather than discovering it accidentally through code order.

The supplied tests run variants of the exact script with controlled constant values. They check messages for each case and make no claim about server-side booking or browser form validation. This narrow test is valuable because it isolates the decision from the interface that will later call it.

Worked practice

Worked exercise 1: Check the upper boundary

Task: requestedSeats and availableSeats are both three, and the event is open. Worked answer: the request fits. The rejection condition uses >, not >=, so equal values are allowed. Changing that operator would incorrectly reject a request for the last available seats.

Worked exercise 2: Reject a numeric-looking string

Task: requestedSeats is '2'. Worked answer: Number.isInteger returns false, so the positive-whole-number message appears. A real form handler should convert deliberately after checking emptiness, then apply this numeric contract.

Worked exercise 3: Predict overlapping failures

Task: isOpen is false and requestedSeats is zero. Worked answer: the closed message wins because that branch is evaluated first. The remaining branches are skipped. This is a decision-priority rule, not evidence that zero became a valid count.

Knowledge check

Question 1

Which operator asks strict equality? A) =. B) ===. C) ==. D) !==.

Check question 1: answer and explanation

Answer: B. Strict equality compares without the coercion performed by loose equality.

Question 2

Which value is truthy? A) ''. B) 0. C) '0'. D) null.

Check question 2: answer and explanation

Answer: C. A nonempty string is truthy even when its contents look like zero.

Question 3

What does Number.isInteger('2') return? A) false. B) true. C) The number 2. D) The string '2'.

Check question 3: answer and explanation

Answer: A. It does not coerce a string into a number.

Question 4

When does the right side of && get skipped? A) When the left side is truthy. B) When the right operand would throw, regardless of the left value. C) Whenever the two operands have different types. D) When the left side is falsy.

Check question 4: answer and explanation

Answer: D. Short-circuit evaluation can avoid evaluating the second operand.

Question 5

Why test a request exactly equal to availability? A) To check an important boundary. B) To establish that every smaller input, including fractions, is valid. C) To replace a separate test just above the availability limit. D) To verify that the boundary is rejected regardless of the policy.

Check question 5: answer and explanation

Answer: A. Boundary tests expose incorrect inclusive or exclusive comparisons.

Sources and further reading