0

let name = window.prompt("Please Enter Your Name ");
let age = parseInt(window.prompt("Please Enter Your age "));

const nameCheck = new Boolean(name);
const ageCheck = new Boolean(age);

if ( nameCheck && ageCheck )
{
   console.log(`Hi ${name}, you were born in ${2020 - age}`)
}
else
{
   alert("You either entered no name, or your age was not a number");
}

The if-block always evaluates to true and executes even if I intentionally enter an empty string or a letter for the age. I thought an empty string has to evaluate to false when converted to Boolean ?

mickl
  • 48,568
  • 9
  • 60
  • 89
Kobby Owen
  • 85
  • 1
  • 8
  • you could instead use `const nameCheck = !!name;` – Addis Jan 17 '20 at 20:41
  • 1
    NameCheck and ageCheck are objects therefore they are evaluated to true. To your code works do not use the Boolean constructor but the Boolean function, I mean just remove the new keyword. –  Jan 17 '20 at 20:42
  • Thanks, removing the "new" really works !!!! – Kobby Owen Jan 17 '20 at 20:47

2 Answers2

3

Boolean doesn't do what you think it does. It's an object, and objects are always truthy:

> typeof new Boolean(false)
"object"
> if (new Boolean(false)) console.log("It's true!");
It's true!

To convert a value to a primitive boolean type instead, a common way is to negate it twice:

const nameCheck = !!name;

You can also invoke Boolean as a function, but I'd stay away from that because it's rather confusing that it doesn't return an actual Boolean:

const nameCheck = Boolean(name);
Thomas
  • 174,939
  • 50
  • 355
  • 478
  • You can find this in the MDN documentation too. "Any object of which the value is not undefined or null, including a Boolean object whose value is false, evaluates to true when passed to a conditional statement. " https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean – PFlans Jan 17 '20 at 20:40
2

Boolean is an object wrapper which always returns truthy value. You can run .valueOf() to get wrapped value or get rid of new:

let x = new Boolean("");

console.log(x === false);
console.log(x.valueOf() === false);

let y = Boolean("");

console.log(y === false);
mickl
  • 48,568
  • 9
  • 60
  • 89
  • 1
    Or just drop the `new`. Although `Boolean("false")` or `new Boolean("false")` will always produce a primitive `true`. – VLAZ Jan 17 '20 at 20:40
  • 1
    @VLAZ which of course is confusing for someone new or coming to JS world from different language. Thanks for your comment ! – mickl Jan 17 '20 at 20:41