Ayan
Ayan

Reputation: 2918

Boolean value tricks if statement

I am getting a custom header value and the values I receive are correct. The expected values are: true, false, undefined.
However, the response based on such value: false is not correct.

Snippet

let isMobileDevice = req.headers["is-mobile-device"];
console.log(isMobileDevice);

if(isMobileDevice) {
    console.log("Mobile client");
    return res.sendStatus(200);
}
else {
    console.log("Web Client");
    return res.sendStatus(200);
}

Output

[0] undefined
[0] Web Client
[0] POST /api/v1/authorization 200 92.690 ms - 2
[0] false
[0] Mobile client
[0] POST /api/v1/authorization 200 76.601 ms - 2
[0] true
[0] Mobile client
[0] POST /api/v1/authorization 200 74.978 ms - 2

I might be doing something wrong but I really can't find where.

Upvotes: 0

Views: 86

Answers (4)

Sagar M
Sagar M

Reputation: 1092

You can also change the if condition as below

if (Boolean(isMobileDevice)) {
    // do something
} else {
    // do something else
}

Upvotes: 0

user11275695
user11275695

Reputation: 26

Don't really know javascript but...

Most likely it's because isMobileDevice is a string type and will always evaluate to true as long as it isn't ""

Try if(isMobileDevice == "true")

Upvotes: 0

Vikash_Singh
Vikash_Singh

Reputation: 1896

Check for the values to be strings as well, not just boolean, since false is not the same as 'false'. Same with true and 'true'.


    let isMobileDevice = req.headers["is-mobile-device"];
    console.log(isMobileDevice);

    if(isMobileDevice==true || isMobileDevice=='true') {
        console.log("Mobile client");
        return res.sendStatus(200);
    }
    else {
        console.log("Web Client");
        return res.sendStatus(200);
    }

Upvotes: 2

axiac
axiac

Reputation: 72306

The values you get in isMobileDevice are not booleans (true, false) but strings ('true', 'false').
When evaluated in boolean context, both are equivalent to true (boolean).

You should compare isMobileDevice against a string:

if (isMobileDevice === 'true') {
    // do something
} else {
    // do something else
}

When used in boolean context (i.e. as conditions) false, 0, "", null, undefined, and NaN are considered false, all the other values are considered true.
Read more about the truthy value in JavaScript: https://developer.mozilla.org/en-US/docs/Glossary/Truthy

Upvotes: 4

Related Questions