If I declare a JavaScript boolean variable like this:
var IsLoggedIn;
And then initialize it with either true
or 1
, is that safe? Or will initializing it with 1
make the variable a number?
var a1 ="true"; var a2 ="false"; Boolean() function in JavaScript: Boolean function returns the boolean value of variable. It can also be used to find boolean result of a condition, expression etc. Note: A variable or object which has value are treated as true boolean values.
JavaScript provides the Boolean() function that converts other types to a boolean type. The value specified as the first parameter will be converted to a boolean value. The Boolean() will return true for any non-empty, non-zero, object, or array.
To declare a Boolean variable, we use the keyword bool. To initialize or assign a true or false value to a Boolean variable, we use the keywords true and false. Boolean values are not actually stored in Boolean variables as the words “true” or “false”.
Because you can't add booleans, so it converts them to numbers first.
Types are dependent to your initialization:
var IsLoggedIn1 = "true"; //string var IsLoggedIn2 = 1; //integer var IsLoggedIn3 = true; //bool
But take a look at this example:
var IsLoggedIn1 = "true"; //string IsLoggedIn1 = true; //now your variable is a boolean
Your variables' type depends on the assigned value in JavaScript.
No it is not safe. You could later do var IsLoggedIn = "Foo";
and JavaScript will not throw an error.
It is possible to do
var IsLoggedIn = new Boolean(false); var IsLoggedIn = new Boolean(true);
You can also pass the non boolean variable into the new Boolean()
and it will make IsLoggedIn boolean.
var IsLoggedIn = new Boolean(0); // false var IsLoggedIn = new Boolean(NaN); // false var IsLoggedIn = new Boolean("Foo"); // true var IsLoggedIn = new Boolean(1); // true
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With