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?
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
.
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]
.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With