문제

Is there a shorthand way of doing this so that the outcome is always true or false?

function trueFalse() {
if( a == 1 ) {
return true;
}else{
return false;
}
}

Something like return true:false; and no need for the else section?

Thanks.

도움이 되었습니까?

해결책

That would be:

function trueFalse(){
  return a === 1;
}

Also, as much as possible, use strict comparison.

다른 팁

(a few years after OP question but this would now also work)

ES6 shorthand would allow you to use a conditional operator:

const trueFalse = a === 1 ? true : false

Or even shorter but a bit less readable:

const trueFalse = a === 1

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top