Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what does && return in javascript expression

Tags:

javascript

I was reading the javascipt code in some application and code was this

getTotalFees:function(){
        return this.grid
        &&this.grid.getStore().sum('fees');
}

Now i am confused what it will return.

IT looks to me like

return a&&b

won't it return true or false rather than b

like image 969
Mirage Avatar asked Jul 29 '26 11:07

Mirage


2 Answers

Logical AND (&&):
expr1 && expr2 Returns expr1 if it can be converted to false; otherwise, returns expr2. Thus, when used with Boolean values, && returns true if both operands are true; otherwise, returns false.

Source

So, basically:
If the first parameter is falsy, it returns that parameter. Else, it literally returns the second parameter.

In your case, this means that, if this.grid exists, it returns this.grid.getStore().sum('fees');

like image 50
Cerbrus Avatar answered Aug 01 '26 02:08

Cerbrus


This is done to protect against calling a method on undefined property, witch would cause an error. So if this.grid is undefined, then undefined is returned.

In expressions if a && b when a equals to false (or in javascript it can be an expression like in Cerburs answer), then a is returned.

Similarly with || operator, the first from the left that equals to true (in javascript not 0, not undefined, not null, not NaN, and not false of course) is returned.

like image 38
Harazi Avatar answered Aug 01 '26 02:08

Harazi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!