简体   繁体   中英

Why does if else statement not work the same way as else if statement?

I am trying to put a cards counting game together. There is multiple ways to write this piece of code, but the thing that makes me think is what the difference is between those to code samples? The first piece of code works fine, but the second gives me undefined.

  if (count > 0) {
       var betHigher = "Bet Higher";
       return betHigher;

   } else {
       count < 0;
       var holdbet = " hold ";
       return holdbet + "" + count;

   }

This gives me undefined. Why is that?


    if (count > 0) {
        var betHigher = "Bet higher";
        return betHigher;

    } else if (count < 0) {
        var holdbet = " hold";
        return holdbet;
    }

}

Your first example has an else which means "anytime count is not greater than 0"

Your second example does not, so if count == 0 it would fail, which is why you get an error/undefined.

The else would handle that

if (count > 0) {
    var betHigher = "Bet higher";
    return betHigher;

} else if (count < 0) {
    var holdbet = " hold";
    return holdbet;
} else {
    // count is equal to 0 here
}

当计数为 0 时,第二个脚本不会传递任何条件,但第一个代码将运行else块。

In your first code example, count < 0 is not being evaluated as an if statement, the result is calculated and then thrown out. It's roughly comparable to calling a function that returns a value but not using the value, both are just expressions to be evaluated. Only two conditions are actually being accounted for- count > 0 and count <= 0 .

The second code example does have this check, but only count > 0 and count < 0 are being accounted for. Note that when count is zero, no return statement is evaluated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM