-4

Im starting to study JavaScript and i dont understand how does the following code work as intended.The goal is to basically ask the user for a number until the number user inputs is greater than 100 or until user doesn't want to input anything and therefore cancels.This code apparently does exactly that:

let num;

do {
  num = prompt("Enter a number greater than 100?", 0);
} while (num <= 100 && num);

What i dont understand it how it doesn't fail since if input in while is 0 then num equals false and loop terminates but for some reason 0 is fine in this example and user is repeatedly promoted each time and code works?

  • 2
    `"0"` is truthy. – Marco Aug 06 '23 at 12:49
  • 1
    JavaScript all sorts of quirks, but in this case it's pretty straightforward what's going on. The `prompt` function returns `string` value, and `"0"` (a string containing the character zero) is different from `0` (the numeric value of zero). You should try to always be aware of the types JavaScript is implicitly assuming. To explicitly convert a stringified number to an actual numerical value, you can use the `parseInt` function. – Andrei Aug 06 '23 at 12:55
  • ^ Nice comment. Note [parseInt](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt) should be supplied with a radix. Or you can use [`Number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/Number). – Andy Aug 06 '23 at 13:28
  • 1
    @Andy According to the very documentation page you linked, the radix argument is optional and defaults to ten, unless the `0x` prefix is used. Remarkably it does not assume leading zeroes to mark an octal number, so it should be okay to use without radix (allowing hexadecimal input can sometimes even be useful). If you think a radix should always be supplied, maybe you can explain why, because right now the comment reads as if you'd say that the docs mandate the existence of the radix argument, which they don't. – CherryDT Aug 06 '23 at 14:02
  • 1
    If you continue to read that document it says "Be careful — this does not always default to 10!" so I'm not sure what more you want me to add. @CherryDT – Andy Aug 06 '23 at 14:26

0 Answers0