6
deletemode = new Boolean(false);

if(deletemode) alert("TRUE"); else alert("FALSE");

alert(deletemode);

I was hoping to see FALSE alert but I am seeing TRUE alert

I read MDN and it read

deletemode = new Boolean(true);

That is the way to create a false boolean variable

But when I run the statements above I see "TRUE" and then in the second alert I see false.

If I do this it does what I expect it to do

if(deletemode===false) 

Is

if(deletemode) 

a JavaScript syntax error?

  • That's looks like expected behavior according to MDN. See the first code example there. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean – Gohn67 Dec 31 '14 at 00:36
  • 2
    On my browser, `deletemode === false` evaluates to `false`, not `true`. – Alnitak Dec 31 '14 at 00:36
  • @Alnitak I think he's talking about the case `if (deletemode)` returns `true`, which appears to be expected behavior. – Gohn67 Dec 31 '14 at 00:37
  • 1
    He said _"if I do this it does what I expect it to do"_ then has the `if (deletemode == false`). – Alnitak Dec 31 '14 at 00:40
  • @Alnitak Sorry, I think I just misunderstood the context of your comment. I do see what you mean. – Gohn67 Dec 31 '14 at 00:44

3 Answers3

7

The reason this is unexpected is because new Boolean(false) returns an object. In JS, all objects evaluate to a truthy value. This is why your test alerted 'TRUE' since the 'if' construct simply checks whether the expression is truthy.

In addition, you should never create a boolean using the Boolean constructor function. Instead, just use the literal values, true or false.

wmock
  • 5,382
  • 4
  • 40
  • 62
3

The === strict equality operator will return false since the Boolean object and the boolean literal are not strictly equal. In fact, even this will return false, because the two newly created objects are not the same object:

new Boolean(true) === new Boolean(true)    // is false

However a deletemode == false test will return true because it will call the .valueOf() method on the object and get the value false, which therefore correctly compares equal to false.

The alert() function always calls .toString() on its parameter, therefore also displaying false instead of the default [Object object].

Alnitak
  • 334,560
  • 70
  • 407
  • 495
1

I think you may find some answers in the following link. The short answer: using the new Boolean() constructor creates a wrapper around your value so that calling the variable always returns true. If all you want to do is store true/false, without any extra functions or logic on the variable holding the value, then you should probably just assign it directly. ie, var deletemode = false

What is the purpose of new Boolean() in Javascript?

Community
  • 1
  • 1
OSBastard
  • 135
  • 10