theateist - 1 year ago 71
Javascript Question

# Why don't logical operators (&& and ||) always return a boolean result?

Why do these logical operators return an object and not a boolean?

``````var _ = (obj.fn && obj.fn() ) || obj._ || ( obj._ = {} );

var _ = obj && obj._;
``````

I want to understand why it returns result of
`obj.fn()`
(if it is defined) OR
`obj._`
but not boolean result.

`var _ = ((obj.fn && obj.fn() ) || obj._ || ( obj._ == {/*soemthign*/}))? true: false` will return boolean.

UPDATE

Note that this are based on my test. And I am not to be relied fully.

It is an expression that does not assign true or false value, rather assigns the calculated value. Lets have a look at this expression.

Now for expression

``````var a = 1 || 2;
//a = 1

//its because a will take the value (which is not null) from left
var a = 0 || 2;
//so for this a=2; //its because the closest is 2 (which is not null)

var a = 0 || 2 || 1;    //here also a = 2;
``````

Now for you expression

``````var _ = (obj.fn && obj.fn() ) || obj._ || ( obj._ = {} );

// _ = closest of the expression which is not null
//in your case it must be (obj.fn && obj.fn())
//so you are gettig this
``````

Now for expression

``````var a = 1 && 2;
//a = 2

var a = 1 && 2 && 3;
//a = 3 //for && operator it will take the fartest value
//unless the evey expression is true

var a = 0 && 2 && 3;
//a = 0
``````

And here

``````var _ = obj && obj._;

//_ = obj._
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download