92

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?

Joe
  • 73,764
  • 18
  • 123
  • 142
mrblah
  • 88,033
  • 134
  • 292
  • 404

8 Answers8

169

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.

Jesse Webb
  • 36,395
  • 25
  • 99
  • 138
Canavar
  • 46,286
  • 17
  • 83
  • 120
20

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
Ólafur Waage
  • 64,767
  • 17
  • 135
  • 193
  • 6
    Don't use new Boolean(); IsLoggedIn will evaluate to true in all of those situations (yes, new Boolean(false) is true). – Miles Jun 25 '09 at 19:33
  • @Miles: new Boolean(false) is false not true – jan Jun 13 '13 at 13:12
  • 5
    @jan: `if (new Boolean(false)) alert ('wat')` See http://stackoverflow.com/a/8695363 – Miles Jun 14 '13 at 03:35
  • @Miles Incredible, as `(new Boolean(false)).toString()) === "false"`, thanks for the link – jan Jun 14 '13 at 13:10
10

As this very useful tutorial says:

var age = 0;

// bad
var hasAge = new Boolean(age);

// good
var hasAge = Boolean(age);

// good
var hasAge = !!age;
pavv
  • 121
  • 1
  • 2
  • probably no real explanation. no one wants to comb through a tutorial you could specify in a tl;dr in your post – Heimi Jun 12 '18 at 12:17
7

If you want IsLoggedIn to be treated as a boolean you should initialize as follows:

var IsLoggedIn=true;

If you initialize it with var IsLoggedIn=1; then it will be treated as an integer.

However at any time the variable IsLoggedIn could refer to a different data type:

 IsLoggedIn="Hello World";

This will not cause an error.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
zpesk
  • 4,275
  • 6
  • 37
  • 60
5

You can use and test uninitialized variables at least for their 'definedness'. Like this:

var iAmNotDefined;
alert(!iAmNotDefined); //true
//or
alert(!!iAmNotDefined); //false

Furthermore, there are many possibilites: if you're not interested in exact types use the '==' operator (or ![variable] / !![variable]) for comparison (that is what Douglas Crockford calls 'truthy' or 'falsy' I think). In that case assigning true or 1 or '1' to the unitialized variable always returns true when asked. Otherwise [if you need type safe comparison] use '===' for comparison.

var thisMayBeTrue;

thisMayBeTrue = 1;
alert(thisMayBeTrue == true); //=> true
alert(!!thisMayBeTrue); //=> true
alert(thisMayBeTrue === true); //=> false

thisMayBeTrue = '1';
alert(thisMayBeTrue == true); //=> true 
alert(!!thisMayBeTrue); //=> true
alert(thisMayBeTrue === true); //=> false
// so, in this case, using == or !! '1' is implicitly 
// converted to 1 and 1 is implicitly converted to true)

thisMayBeTrue = true;
alert(thisMayBeTrue == true); //=> true
alert(!!thisMayBeTrue); //=> true
alert(thisMayBeTrue === true); //=> true

thisMayBeTrue = 'true';
alert(thisMayBeTrue == true); //=> false
alert(!!thisMayBeTrue); //=> true
alert(thisMayBeTrue === true); //=> false
// so, here's no implicit conversion of the string 'true'
// it's also a demonstration of the fact that the 
// ! or !! operator tests the 'definedness' of a variable.

PS: you can't test 'definedness' for nonexisting variables though. So:

alert(!!HelloWorld);

gives a reference Error ('HelloWorld is not defined')

(is there a better word for 'definedness'? Pardon my dutch anyway;~)

KooiInc
  • 104,388
  • 28
  • 131
  • 164
  • You might like to retry your string cases with an empty string `thisMayBeTrue = '';` - you won't get the same results since an empty string is falsy. _"PS: you can't test 'definedness' for nonexisting variables though"_ - Sure you can: `typeof HellowWorld === 'undefined'`. – nnnnnn Aug 13 '12 at 03:25
2

How about something like this:

var MyNamespace = {
    convertToBoolean: function (value) {
        //VALIDATE INPUT
        if (typeof value === 'undefined' || value === null) return false;

        //DETERMINE BOOLEAN VALUE FROM STRING
        if (typeof value === 'string') {
            switch (value.toLowerCase()) {
                case 'true':
                case 'yes':
                case '1':
                    return true;
                case 'false':
                case 'no':
                case '0':
                    return false;
            }
        }

        //RETURN DEFAULT HANDLER
        return Boolean(value);
    }
};

Then you can use it like this:

MyNamespace.convertToBoolean('true') //true
MyNamespace.convertToBoolean('no') //false
MyNamespace.convertToBoolean('1') //true
MyNamespace.convertToBoolean(0) //false

I have not tested it for performance, but converting from type to type should not happen too often otherwise you open your app up to instability big time!

TruMan1
  • 27,054
  • 46
  • 150
  • 273
2

Variables in Javascript don't have a type. Non-zero, non-null, non-empty and true are "true". Zero, null, undefined, empty string and false are "false".

There's a Boolean type though, as are literals true and false.

Eugene Morozov
  • 13,126
  • 3
  • 23
  • 31
  • JS _variables_ don't have a type in the sense that you can't declare a variable that will only hold integers or strings (as happens in some other languages), but the particular _value_ held by the variable at any given time will always have a type. And the type matters as can be shown with a simple example like `2 + 2` vs `"2" + 2`. See also the [`typeof` operator](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/typeof). – nnnnnn Aug 13 '12 at 03:31
1

The variable will become what ever type you assign it. Initially it is undefined. If you assign it 'true' it will become a string, if you assign it true it will become a boolean, if you assign it 1 it will become a number. Subsequent assignments may change the type of the variable later.

AnthonyWJones
  • 178,910
  • 32
  • 227
  • 302