Ajay Gupta
Ajay Gupta

Reputation: 2033

What is the difference between 0/1 and true/false in JavaScript

Recently I was trying to accomplish a feature for my app. I needed to use boolean values to turn on or off features.

I tried this:

.env.development

REACT_APP_IS_FEATURE_AVAILABLE = 0

.env.production

REACT_APP_IS_FEATURE_AVAILABLE = 1

features.js

const { REACT_APP_IS_FEATURE_AVAILABLE } = process.env
export default {
    IS_FEATURE_AVAILABLE: REACT_APP_IS_FEATURE_AVAILABLE //
}

Now assuming this is in Development mode, when I do:

index.js

import Features from "./features.js";
if(Features.IS_FEATURE_AVAILABLE) {
    return (<div>Markup here!</div>)
};

But, regardless of what the value of IS_FEATURE_AVAILABLE is, the if is always passing.

I did figured a way out of this, and its working well and good. But I am still confused why this wasn't working.


In response to this answer: https://stackoverflow.com/a/55720488/8349557 here's what I tried:

comparing 0 is equal to true or not

Upvotes: 2

Views: 916

Answers (1)

Jaromanda X
Jaromanda X

Reputation: 1

at a guess, since "environment variables" in every OS I've worked with are always strings what you're essentially doing is

if("0")

And since any non-empty string is truthy, and true is truthy, the result is true

You can confirm this by

console.log('!!"0" is', !!"0"); // true, therefore "0" is truthy
console.log('!!0 is', !!0); // false, therefore 0 is falsey

try

const { REACT_APP_IS_FEATURE_AVAILABLE } = process.env
export default {
    IS_FEATURE_AVAILABLE: +REACT_APP_IS_FEATURE_AVAILABLE //
}

The + coerces the value to be a number

or, to make it CLEAR

const { REACT_APP_IS_FEATURE_AVAILABLE } = process.env
export default {
    IS_FEATURE_AVAILABLE: "1" === REACT_APP_IS_FEATURE_AVAILABLE //
}

Now IS_FEATURE_AVAILABLE is a boolean

Upvotes: 3

Related Questions