Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create JavaScript boolean variable

Tags:

javascript

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?

like image 487
Hender Elstein Avatar asked Dec 31 '14 00:12

Hender Elstein


3 Answers

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.

like image 163
wmock Avatar answered Sep 25 '22 10:09

wmock


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

like image 28
Alnitak Avatar answered Sep 26 '22 10:09

Alnitak


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?

like image 40
OSBastard Avatar answered Sep 26 '22 10:09

OSBastard