Вопрос

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