I find the likelihood of comparing JavaScript. I wanted to find an example of how complicated comparisons are and how errors can occur in some situations.
I thought about where some input variable remains undefined, and compares to zero. Since undefined is false when converting to Boolean, and zero is false when converting to Boolean, I decided to check the following code:
var x; //Here x should be initialized but due to some circumstances is not if(x == 0){ //This should run }
Amazing ...
Boolean(undefined) //false Boolean(0) //false x //undefined x == 0 //false
Why is this so?
This behavior is specified in the specification. Abstract equality comparison algorithm.
From specification
x == y, x y - , true false. :
x == y
x
y
Type(x) Type(y), ... ...
Type(x)
Type(y)
x null, y - undefined, true.
null
comparison x == ToNumber(y)
ToNumber(x) == y
x == ToNumber(y)
comparison x == ToPrimitive(y)
ToPrimitive(x) == y
undefined (0) , , , , undefined., null, true, , 10., "return false".
undefined
0
10.
return false
Boolean(undefined) //false Boolean(0) //false
Boolean false , 0, null, undefined, "" ( ) ..
Boolean
false
, undefined == 0
undefined == 0
This is not deep. If you want to compare value and type, you can use triple '='
if(x === 0){ //This should run }
Otherwise, undefined == null, etc.
Source: https://habr.com/ru/post/1660825/More articles:Java Spring - return from asynchronous callback? - javaEquivalent to ComputeIfAbsent in Java 7 - javaIs there an “invisible” hyphen in Unicode / HTML? - htmlSQL Inner Join 3 Tables - sqlTips for breaking title bar in Plone - htmlSaving communications on the network - mysql - sqlСоздать шаблон заголовка комментария по умолчанию в R? - rGeneral condition with aiohttp web server - pythonCan I add a channel to a specific cond environment? - pythonTypescript error TS2345 on regular express code - typescriptAll Articles