๐ŸŽ“ A1Learner
๐Ÿ”
0 of 55 lessons completed

JavaScript Comparisons

A comparison is a test that answers true or false. Comparison operators compare two values, and logical operators combine tests.

Strict equality

Each comparison answers with true or false. The type must match too, so the number 5 and the text 5 differ.

console.log(5 === 5);
console.log(5 === "5");
console.log(5 !== "5");

Greater and smaller

These operators compare the size of two numbers. Each line prints the answer to one test.

console.log(7 > 3);
console.log(7 < 3);
console.log(7 >= 7);
console.log(2 <= 1);

Logical operators

The first three lines test pairs with && and ||. The last line flips true with the ! operator.

console.log(true && true);
console.log(true && false);
console.log(false || true);
console.log(!true);

Example

let score = 72;
let passed = score >= 60;
let word = passed ? "pass" : "fail";
console.log("Passed:", passed);
console.log("Result:", word);
console.log("High score:", score > 90 && passed);

Key points

  • ===: strict equality, true only when the value and the type both match
  • Type: the kind of a value, like a number or a piece of text
  • Loose equality with == is the risky old form of the test.
  • && needs both sides true, and || needs at least one side true.
  • ! flips a result, turning true into false and false into true.
  • Ternary operator: an operator that picks one of two values from a test

In this example, score starts at 72. The >= test stores true in passed, since 72 is at least 60. The ternary operator reads passed and picks the word pass. The last line combines a size test and passed with &&, and the answer is false.

Try it Yourself

Edit the code, then press Run.

Runs in your browser โ€” the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.

Exercise

What does 5 === "5" give?