JavaScript if(x) vs if(x==true) -
in javascript , in cases following statements won't logically equal ?
if(x){} and
if(x==true){} thanks
they not @ equal.
if (x) checks if x truthy later checks if boolean value of x true.
for example,
var x = {}; if (x) { console.log("truthy"); } if (x == true) { console.log("equal true"); } not object, string (except empty string), number (except 0 (because 0 falsy) , 1) considered truthy, not equal true.
as per ecma 5.1 standards, in if (x), truthiness of x decided, per following table
+-----------------------------------------------------------------------+ | argument type | result | |:--------------|------------------------------------------------------:| | undefined | false | |---------------|-------------------------------------------------------| | null | false | |---------------|-------------------------------------------------------| | boolean | result equals input argument (no conversion). | |---------------|-------------------------------------------------------| | number | result false if argument +0, −0, or nan;| | | otherwise result true. | |---------------|-------------------------------------------------------| | string | result false if argument empty | | | string (its length zero); otherwise result | | | true. | |---------------|-------------------------------------------------------| | object | true | +-----------------------------------------------------------------------+ note: last line object, includes both objects , arrays.
but in later case, per the abstract equality comparison algorithm,
if type(x) boolean, return result of comparison tonumber(x) == y. if type(y) boolean, return result of comparison x == tonumber(y). value of x converted number , number checked against true.
note:
in javascript, true 1 , false 0.
console.log(1 == true); # true console.log(0 == false); # true
Comments
Post a Comment