Saturday, November 9, 2024

JavaScript, undefined with comparison operators

In JavaScript, when one of the operands is undefined in a comparison operation, the result depends on the type of comparison being used:

Loose Equality (==):

  1. undefined == undefined evaluates to true.
  2. undefined == null evaluates to true (because null and undefined are considered loosely equal).
  3. undefined == <any other value> (such as a number, string, or boolean) evaluates to false.

Strict Equality (===):

  1. undefined === undefined evaluates to true.
  2. undefined === null evaluates to false (because they are different types).
  3. undefined === <any other value> (such as a number, string, or boolean) evaluates to false.

Comparison Operators (<, >, <=, >=):

  1. When using comparison operators with undefined, JavaScript converts undefined to NaN (Not-a-Number).
  2. Any comparison with NaN (except !== and ===) will always return false.
  3. For example, undefined < 5 or undefined > 5 will return false.

Examples:

console.log(undefined == undefined); // true
console.log(undefined == null); // true
console.log(undefined === undefined); // true
console.log(undefined === null); // false
console.log(undefined < 5); // false
console.log(undefined > 5); // false

No comments:

Post a Comment

Hot Topics