简体   繁体   中英

Why does my `if(result !== "false")` return true?

I make an ajax call to fetch data. If it exists, eg the result is set I´d like to run another function.

JS

success: function(result){ console.debug(result); console.log(result);
    if(result !== "false" || result !== ""){
        console.log('passed');    
    }

In console I have except "Passed".

The result is empty, but still my if statement evaluates to true. Why?

This is what I send as result. And it´s empty...

PHP

$row = $stmt->fetch();
echo $row['objekt_nr'];

If the result is "false" then it is NOT an empty string, and the right hand side of the OR is true.

If the result is "" then it is NOT "false" and the left hand side of the OR is true.

If it is anything else, then both sides of the OR statement are true.

Either way, the OR statement is true.

You want an AND not an OR.

The conditional result !== "false" || result !== "" result !== "false" || result !== "" will always evaluate true since result can, at best, be one of the two values. In order for the conditional to be false, it result would have to be both "" and "false" at the same time!

For example:

  • if result === "false" then result !== "" must be true (as result is "false" , not "" )

  • if result === "" then result !== "false" must be true (as result is "" , not "false" )

  • if result is neither "" nor "false" , then both sides are true, evaluating to true.

What are you actually trying to check for?

if(result !== "false" && result !== "") would be true if result is neither "false" nor ""

if(result === "false" || result === "") would be true if result is either "false" or ""

Your || needs to be an &&.

The statement if (result !== "false" || result !== "") will always be true! The result string can never both "false" and "" at the same time... which is the only way the statement could ever resolve to false.

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