Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript && opertor in return statement

Tags:

javascript

I have a piece of JavaScript code as follows:

function main(condition){
    if(condition){
        doSomething();
        return obj;
    }
}

now I want to refactor this code to get rid of the "if" statement. Here is what I want to do

function main(condition){
    var doSomethingAndReturnObj = function(){
        doSomething();
        return obj;
    }
    return condition && doSomethingAndReturnObj();
}

here is where I need help. The caller of main function expects a return value of "undefined" or an obj. In my refactored code, would my

return condition && doSomethingAndReturnObj();

convert the return value to a true and false type?

Thanks for your replies.

like image 742
Wei Ma Avatar asked Jul 31 '26 01:07

Wei Ma


1 Answers

The short answer is: no, && does not convert things to Boolean values.

&& only continues if it gets a truthy value, returning the first falsy value, or the last value, meaning:

undefined && true == undefined
true && true      == true
true && false     == false
1 && 2 && 3       == 3
1 && 2 && 0 && 4  == 0

So if your condition is falsy, e.g. false or undefined, it will return that exact value. If your condition is truthy, it will return whatever doSomethingAndReturnObj() returns.

falsy values for reference: null, undefined, 0, false, NaN, "". everything else is truthy.