UNB/ CS/ David Bremner/ teaching/ cs2613/ books/ mdn/ Reference/ Operators/ Less than (<)

The less than (<) operator returns true if the left operand is less than the right operand, and false otherwise.

Syntax

x < y

Description

The operands are compared with multiple rounds of coercion, which can be summarized as follows:

Other operators, including >, >=, and <=, use the same algorithm as <. There are two cases where all four operators return false:

For all other cases, the four operators have the following relationships:

x < y === !(x >= y);
x <= y === !(x > y);
x > y === y < x;
x >= y === y <= x;

Note: One observable difference between < and > is the order of coercion, especially if the coercion to primitive has side effects. All comparison operators coerce the left operand before the right operand.

Examples

String to string comparison

"a" < "b"; // true
"a" < "a"; // false
"a" < "3"; // false

String to number comparison

"5" < 3; // false
"3" < 3; // false
"3" < 5; // true

"hello" < 5; // false
5 < "hello"; // false

"5" < 3n; // false
"3" < 5n; // true

Number to Number comparison

5 < 3; // false
3 < 3; // false
3 < 5; // true

Number to BigInt comparison

5n < 3; // false
3 < 5n; // true

Comparing Boolean, null, undefined, NaN

true < false; // false
false < true; // true

0 < true; // true
true < 1; // false

null < 0; // false
null < 1; // true

undefined < 3; // false
3 < undefined; // false

3 < NaN; // false
NaN < 3; // false

Comparison with side effects

Comparisons always coerce their operands to primitives. This means the same object may end up having different values within one comparison expression. For example, you may have two values that are both greater than and less than the other.

class Mystery {
  static #coercionCount = -1;
  valueOf() {
    Mystery.#coercionCount++;
    // The left operand is coerced first, so this will return 0
    // Then it returns 1 for the right operand
    return Mystery.#coercionCount % 2;
  }
}

const l = new Mystery();
const r = new Mystery();
console.log(l < r && r < l);
// true

Warning: This can be a source of confusion. If your objects provide custom primitive conversion logic, make sure it is idempotent: multiple coercions should return the same value.

Specifications

Browser compatibility

See also