Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring a boolean in JavaScript using just var

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?

like image 419
mrblah Avatar asked Mar 17 '09 11:03

mrblah


People also ask

Can var be boolean?

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.

How do you initialize a boolean value in JavaScript?

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.

How do you declare a boolean variable?

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”.

Can you add booleans in JavaScript?

Because you can't add booleans, so it converts them to numbers first.


2 Answers

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.

like image 105
Canavar Avatar answered Sep 16 '22 15:09

Canavar


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 
like image 25
Ólafur Waage Avatar answered Sep 16 '22 15:09

Ólafur Waage