why in JavaScript's: obj = new Boolean(false) , (obj && true) is true, and (obj || false) is false? -


this question has answer here:

to see result, open console in google chrome, following:

obj = new boolean(false) "obj && true: " + (obj && true) "obj || true: " + (obj || false) 

and:

(obj && true) == true   // true (obj || false) == true   // false 

and why

(obj || false) 

returns boolean object, instead of boolean value?

(hmm.. put summary answer below)

there 2 concepts need considered here:

obj = new boolean(false) 

creates object, values false. object considered truthy, it's value (which tostring() or valueof()) of course boolean value false.

(x||y) 

returns first truthy value (or if none present, last falsy value) and

(x&&y) 

returns first falsy value (or if none present, last truthy value).

so (obj||false) returns boolean object, (obj&&true) returns second (true) value.

the further preceeding depends on context of expression.

"obj && true: " + (obj && true) 

demands string context, tostring() called on boolean object, returning it's value false (while object truthy!).

furthermore,

(obj && true) == true compares true == true of course true. however,

(obj || true) == true lot of type coercion §11.9.3 , compares

toprimitive(obj) == tonumber(true) (§9.1 , §9.3) results in nan == 1 yields false.

the results more predictable if use strict equality operator §11.9.6.


Comments

Popular posts from this blog

php - mySql Join with 4 tables -

css - Text drops down with smaller window -

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -