Michael Wall Michael Wall -4 years ago 175
Javascript Question

React-Native How to use a Boolean

I pretty new to react native and I have a very basic question.
I unfortunately don't know how to work with a Boolean in React-Native.
I tried to find a solution on google but apparently my question is so simple that no-one has asked it.

Where in my code do I have to declare the boolean?

How can I change the value?

What is the right way to compare it ? (I think if(myBoolean===true) but I am not completely sure.)

I am sry to bother you all with that stupid question,

Greetings,

Michael

Answer Source

This is more a JS question than an React Native one, since React Native uses standard-compliant JavaScript as programming language. So, going through all your questions:

Where in my code do I have to declare the boolean?

The boolean is one of the 6 data type primitives in JS, along with null, undefined, number, string and Symbol (ES6 only). So you can just create a boolean the way you would with any of those. For instance:

var myBoolean = true;

You can create the boolean in pretty much any part of your code: inside a function, as a global variable, as an object property...

Remember than JS is a dynamically weakly typed language, which means that if you assign a different type value to myBoolean, it would then be of that type. For instance:

var myBoolean = true; // I'm a boolean
myBoolean = "A string"; // I'm a string

How can I change the value?

We just changed its value by initializing the variable, but it would be as simple as:

var myBoolean = true; // I'm a boolean
myBoolean = false; // I'm a string

What is the right way to compare it ? (I think if(myBoolean===true) but I am not completely sure.)

Your approach is totally correct, but you can also do some other things in this case. This are all valid:

if(myBoolean === true) // Will check that myBoolean has the same value and type as true 
if(myBoolean == true) // Will check that myBoolean has the same value as true
if(myBoolean) // Will check that myBoolean has a 'truthy' value (anything that is not a false, 0, "", null, undefined or NaN (not a number).
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download