Question

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.

Était-ce utile?

La solution

That would be:

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

Also, as much as possible, use strict comparison.

Autres conseils

(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

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top