Why {} <function () {}?

While I was looking at 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 only tested this in Firefox, and I'm sure I can dig out the details in the ECMAScript 2.6.2 specification, but TBH I feel lazy.

+6
javascript operators logical-operators
Nov 14 2018-11-11T00:
source share
4 answers

JavaScript casting does the comparison basically

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

so what are you just doing

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

which is a comparison of a lexicographic string.

+17
Nov 14 '11 at 1:44
source share
β€” -

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

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

[ less than f .

+8
Nov 14 '11 at 1:44
source share
 alert(({})) -> [object Object] alert((function(){})) -> function () {} 

[ preceded by f , therefore ({}) < (function () {}) .

Yes, this is stupid .;)

+4
Nov 14 '11 at 1:44
source share

quite simple and simple ( internally they are both converted to strings ) because in Javascript

If the object is compared to a number or a string, JavaScript tries to return the default value for the object. Operators try to convert an object to a primitive value, a String or Number value, using the valueOf and toString methods for objects.

therefore, when both are compared, both objects are converted to a string using the Tostring internal method

  a.toString() "[object Object]" b.toString() "function () { }" 

therefore, b will be greater than a (large string) why b> a is true

0
Nov 14 '11 at 1:50
source share



All Articles