I do not understand what's going on
var x=new Boolean(false)
if(x){
console.log('plus')
}
console.log(x==false) //true
Why if(x)
returns true
?
I do not understand what's going on
var x=new Boolean(false)
if(x){
console.log('plus')
}
console.log(x==false) //true
Why if(x)
returns true
?
Says so in the docs:
Any object whose value is not undefined or null, including a Boolean object whose value is false, evaluates to true when passed to a conditional statement. For example, the condition in the following if statement evaluates to true
x = new Boolean(false);
if (x) {
// ...this code is executed
}
Directly from MDN.
See MDN docs : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean .
It is stated :
Any object whose value is not undefined or null, including a Boolean object whose value is false, evaluates to true when passed to a conditional statement.
It's as simple as this:
x
is a Boolean
object. (Logging it will show: Boolean {}
)
All objects evaluate to true
(See the first paragraph under "Description")
Object is truthy. See http://james.padolsey.com/javascript/truthy-falsey/
so evaluating it without the implicit type conversion (when comparing to false
) is true.
You are using the Boolean function incorrectly: http://www.w3schools.com/js/js_booleans.asp
What you're looking for is:
var x = false;
if (Boolean(x)){
}
However, since you already know x will be true or false, and you're not evaluating an expression to see if it's true or false (as per the link), you don't need the function Boolean()
A Boolean class is not a primitive value. when you check
if (someObject)
it will return true because
Boolean(someObject)
will always return true.
You have a couple of options here: 1. Use
if (valueOf(x))
to get the primitive value again
2. Remove the 'new' keyword
x = Boolean(false)
So you get the value of the Boolean function
Take a look at What is the purpose of new Boolean() in Javascript?