-2

I´m really confused. Maybe anyone can help me? The problem is the following:

var isSignInside = new Boolean(someCondition);

if (!isSignInside) {
    //doStuff
}
else {
    //doOtherStuff
}

Now, if isSignInside is false (the debugger told me), the script still jumps to //doOtherStuff. How can this be? The rest of the snippet isn´t of relevance, but I can share it if asked. Surely there is an easy explanation i don´t see. Thanks in advance. Edit: The someCondition really is a custom method "forced" to return a bool instead of (otherwise) a string. Edit: Just used the function directly in the if. Needed some tricky paranthesis, but works now. Thanks for the hint that a (boolean) object can never be === to a static boolean primitive. Hell this forum is fast.

L. Riemer
  • 419
  • 5
  • 10

3 Answers3

4

When you create a Boolean object, it's an object. A reference to it, regardless of the boolean primitive value it represents, will always test as truthy just like any other non-null object reference.

There's generally no point in constructing a Boolean instance like that:

var isSignInside = !!someCondition;

That'll give you a boolean primitive that reflects the truthy/falsy state of your condition.

Pointy
  • 371,531
  • 55
  • 528
  • 584
2
if(new Boolean(false)) alert("hehe");

Actually, isSignedInside is not a boolean, but a boolean object (thanks to the new). You may want to get its primitive value for comparison:

if( (new Boolean(false)).valueOf() ) alert("hehe");

Or even easier, take the value directly.

Jonas Wilms
  • 106,571
  • 13
  • 98
  • 120
1

Well that's not how that's done. You want to use a boolean primitive. What you're trying to do is done this way:

var isSignInside = (someCondition);
if (isSignInside === false) {
   //doStuff
}
else {
    //doOtherStuff
}

https://jsfiddle.net/catbadger/pxrteq59/

catbadger
  • 1,427
  • 14
  • 25