Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is {} < function(){}?

While I was messing around with truth tables in JavaScript, I noticed that the following evaluates to true:

var a, b, c;
a = {};
b = function(){};
c = a < b;
console.log(c);

Why?

I've only tested this in Firefox, and I'm sure I could dig up the details in the ECMAScript 2.6.2 spec, but TBH I'm feeling lazy.

like image 569
zzzzBov Avatar asked Nov 14 '11 01:11

zzzzBov


3 Answers

JavaScript type coercion makes the comparison essentially

String({}) < String(function(){})

so essentially you are just doing

"[object Object]" < "function (){}"

which is a lexicographic string comparison.

like image 52
David Hu Avatar answered Oct 10 '22 20:10

David Hu


Javascript compares objects by calling valueOf() or toString().
Since neither operand has a valueOf() method, it will compare the toString()s.

({}).toString() is [object Object].
(function() { }).toString() is function() { }.

[ is less than f.

like image 36
SLaks Avatar answered Oct 10 '22 20:10

SLaks


alert(({}))            -> [object Object]
alert((function(){}))  -> function () {}

[ comes before f, hence ({}) < (function () {}).

Yes, it's silly. ;)

like image 21
deceze Avatar answered Oct 10 '22 19:10

deceze