Why is the else executed when entering zero, but the conversion from the if condition is performed?

  • 0
    <!DOCTYPE html>
    <html lang="en">
    <head>
     <meta charset="UTF-8">
     <meta name="viewport" content="width=device-width, initial-scale=1.0">
     <title>JS test</title>
    </head>
    <body>
      <script type="text/javascript">
    
        let num = prompt('введите число:', 0);
    
        if ( num = Number(num) ){
          alert('in if');
          if (num > 0) {
            alert(typeof(num));
            alert('1');
          }else if (num < 0){
            alert(typeof(num));
            alert('-1');
          }else if(num == 0){
            alert('0');
          }
        }else{
          alert('in else');
          alert(typeof(num));
          alert('Это не число!');
        }
    
      </script>
    </body>
    </html>
    JavaScript Anonymous, Mar 22, 2019

  • 3 Answers
  • 0
    The first part should be replaced with

    let num = Number(prompt('введите число:', 0));
    if (!isNan(num ))


    and now there is assignment instead of comparison
    Juliette Keller

  • 0
    if (num = Number (num)) {}

    here comes the assignment where the result is num = 0

    if (0) condition is false, we fall into else
    Nathan Holder

  • 0
    Because zero is a lie in the condition.



    There are 7 false values ​​in JS: false , null , 0 , 0n , "" , NaN , undefined .

    You just have to remember it.



    Specifically your condition:

    if (num = Number (num)) {

    you can try replacing with:

    if ((num = Number (num)) || num === 0) {

    Then it will go to else only in case of an error.

    Of course, this is far from the only way and not the most beautiful one. But the essence of the error, I hope, is clear.
    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!