Lesson · JavaScript Basics

Operators and conditional logic

A condition turns a rule into a choice the program can evaluate.

What you will learn

  • Use comparison operators
  • Combine booleans with logical operators
  • Order if and else if branches carefully

Compare values

Operators such as >, >=, <, and <= compare numeric values. Strict equality checks whether values match without coercion. A comparison produces a boolean that can be used directly in a conditional or saved in a descriptive variable when the rule needs a name.

Choose a branch

An if block runs when its condition is true; else handles the other case. Use else if when there are several mutually exclusive outcomes. The first matching branch wins, so order the checks intentionally, particularly when a broad condition might also include values intended for a narrower case.

Combine rules

The && operator means both conditions must be true, while || means at least one must be true. The ! operator negates a boolean. Parentheses can make a compound rule clearer and protect readers from needing to remember precedence for a long expression.

Test boundary values

For rules involving a threshold, test a value below the threshold, a value exactly on it, and a value above it. This simple set reveals many off-by-one mistakes. Use the same units and types on both sides of a comparison so the rule reflects the intended meaning.

Avoid accidental truthiness

JavaScript conditions accept truthy and falsy values, not only literal booleans. Empty strings, zero, null, undefined, and NaN are falsy, while many other values are truthy. For a rule about a particular value, compare it explicitly instead of relying on this coercion when it could hide an unexpected input.

Javascript example
const score = 72;
if (score >= 80) {
  console.log('Strong result');
} else if (score >= 40) {
  console.log('Keep practising');
} else {
  console.log('Review the basics');
}
Expected output
Keep practising

Practice exercise

Print 'eligible' only when a person is at least 18 and has permission.

Show a hint

Combine the age comparison and permission boolean with &&.

Show one possible solution

Use if (age >= 18 && hasPermission) and an else branch for the other case.

Quick check

What does && require?

Frequently asked questions

When should I use a switch statement?
<p>A switch can make several exact-value cases clearer, while if/else is usually more direct for ranges or combined conditions. Choose the form that makes the rule easiest to read.</p>