Create JavaScript Boolean

deletemode = new Boolean(false); if(deletemode) alert("TRUE"); else alert("FALSE"); alert(deletemode); 

I was hoping to see a FALSE alert, but I see TRUE alert

I read MDN and read

 deletemode = new Boolean(true); 

Here's how to create a false boolean variable

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

If I do, he does what I expect from him.

 if(deletemode===false) 

Is an

 if(deletemode) 

JavaScript syntax error?

+6
source share
3 answers

The reason this is unexpected is because new Boolean(false) returns an object. In JS, all objects are evaluated in truth. This is why your test warned "TRUE" because the "if" construct simply checks to see if the expression is plausible.

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

+7
source

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, the deletemode == false test will return true because it will call the .valueOf() method and get false , which therefore is correctly compared to false .

The alert() function always calls .toString() in its parameter, therefore it also displays false instead of the standard [Object object] .

+3
source

I think you can find the answers in the following link. Short answer: Using the new Boolean () constructor creates a wrapper around your value, so calling the variable always returns true. If all you want to do is store true / false, without any additional functions or logic for a variable containing a value, then you probably should just assign it directly. those. var deletemode = false

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

+1
source

Source: https://habr.com/ru/post/980335/


All Articles