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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With