Reputation: 1433
Regarding conditional if/else statements, are the following examples functionally equivalent?
function isEntering() {
if (this.stage === 'entering') {
return true;
} else {
return false;
}
}
function isEntering() {
if (this.stage === 'entering') {
return true;
} return false;
}
function isEntering() {
if (this.stage === 'entering') {
return true;
}
}
isEntering = (this.stage === 'entering') ? true : false;
If so, I'd use the most terse of the options. But only if the four are functionally equivalent.
Upvotes: 0
Views: 168
Reputation:
If expr
is a boolean expression, as it is here, then there is no need to write
if (expr) return true;
else return false;
or to write
if (expr) x = true;
else x = false;
or to ever write
expr ? true : false
because being a boolean expression, expr
can be returned, or assigned, directly:
return expr;
x = expr;
The tersest alternative is one you didn't give:
function isEntering() { return this.stage === 'entering'; }
Upvotes: 4
Reputation: 5734
They are not all equivalent. The first two are equivalent, but:
function isEntering() {
if (this.stage === 'entering') {
return true;
}
}
Would return undefined
if this.stage !== 'entering'
.
Also:
isEntering = (this.stage === 'entering') ? true : false;
Is not defining a function as the other examples.
As mentioned you can add:
isEntering = () => this.stage === 'entering';
If you don't need a function you can use:
isEntering = this.stage === 'entering'
Upvotes: 1