Are these JS conditional statements functionally equivalent?

有些话、适合烂在心里 提交于 2019-12-12 04:18:58

问题


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.


回答1:


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'; }



回答2:


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'


来源:https://stackoverflow.com/questions/44830141/are-these-js-conditional-statements-functionally-equivalent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!