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 &&a开发者_JS百科mp; 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.
JavaScript's &&
operator is coalescing.
js> 0 && 7
0
js> 1 && 7
7
The value returned by doSomethingAndReturnObj() will not be converted to true or false.
精彩评论