Pergunta

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.

Foi útil?

Solução

That would be:

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

Also, as much as possible, use strict comparison.

Outras dicas

(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

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top