1

I am new to Javascript and I noticed when a variable is undefined, comparing a number returns false as below. Why does comparing undefined with numbers return false?

var a = undefined;
console.log(a < 10);
console.log(10 < a);
console.log(a == 10);
Towkir
  • 3,889
  • 2
  • 22
  • 41
Seungho Lee
  • 1,068
  • 4
  • 16
  • 42
  • 2
    What would you expect those to return? Certainly not true – charlietfl Nov 20 '18 at 04:41
  • Read: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined – Randy Casburn Nov 20 '18 at 04:41
  • Because you are comparing the global `undefined` property that represents the primitive value `undefined` against a `number` and that returns `false`.. More about [undefined](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined) – Yosvel Quintero Nov 20 '18 at 04:44

1 Answers1

3

This is how works in JavaScript.

Number(undefined) // NaN
NaN == NaN // false
NaN < 0 // false
NaN > 0 // false

So, while you compare it forces to check like:

Number(undefined) < 10
// undefined is coerced to check with number

And thus,

undefined == 10 // false
undefined > 10 // false
undefined < 10 // false
Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231