Declaring a boolean in JavaScript using just var

mrblah picture mrblah · Mar 17, 2009 · Viewed 312.3k times · Source

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?

Answer

Canavar picture Canavar · Mar 17, 2009

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.