Boolean function in JavaScript
You can use the Boolean
function to convert a value to a boolean (true or false).
Don't confuse it with new Boolean
. If you use the new
operator, it will create an instance of Boolean.
var x = Boolean(false); // x becomes false
if (x) console.log('hey'); // console doesn't execute.
typeof x; // "boolean"
var y = new Boolean(false); // y becomes a Boolean object.
if (y) console.log('hey'); // it logs 'hey'.
typeof y; // "object"
Learn more in falsy values and truthy values.
You can also use the double not (!!) to do equivalent conversions.
Questions
What's the output?
Boolean(0);
What's the output?
Boolean(new Boolean(false));
What's the output?
Boolean(null);
What's the output?
Boolean(NaN);
What's the output?
Boolean(undefined);
What's the output?
Boolean(false);
What's the output?
//prettier-ignore
Boolean("");
What's the output?
Boolean('false');
What's the output?
Boolean(!!false);
What's the output?
Boolean(new Boolean(!!false));