Seungho Lee
Seungho Lee

Reputation: 1155

Why does comparing value with undefined returns false in JavaScript?

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);

Upvotes: 1

Views: 1407

Answers (1)

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85545

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

Upvotes: 3

Related Questions