Why is {} < function(){}?

爷,独闯天下 提交于 2019-12-04 06:10:50

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.

SLaks

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.

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

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

Yes, it's silly. ;)

pretty simple and easy ( internally they are both converted to strings ) this is because in Javascript

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

so when both are compared both objects are converted to string using the internal Tostring method

    a.toString()
"[object Object]"

b.toString()
"function () { }"

hence b will be greater than a ( larger string ) that's why b > a is true

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!