Best way to prevent/handle divide by 0 in javascript

后端 未结 8 2009
天命终不由人
天命终不由人 2020-12-01 09:12

What is the best way to prevent divide by 0 in javascript that is accepting user inputs. If there is no particular way to achieve this what would be the best way to handle s

相关标签:
8条回答
  • 2020-12-01 10:08

    what would be the best way to handle such a situation so as to not prevent other scripts from executing

    Division by zero doesn't seem to prevent other scripts from execution in JavaScript:

    var a = 20;
    var b = 0;
    var result = a/b;
    console.log(result); // returns Infinity
    

    If you want something different to happen in case of division by zero, you could use

    function divideIfNotZero(numerator, denominator) {
      if (denominator === 0 || isNaN(denominator)) {
            return null;
      }
      else {
            return numerator / denominator;
      }
    }
    
    0 讨论(0)
  • 2020-12-01 10:10

    To prevent (unwanted) execution

    1. Always verify critical user input and/or results
    2. Use logic and/or callbacks you can prevent to execute
    3. On HTML forms etc. you can use i.e. return false; as value to stop submission.
    0 讨论(0)
提交回复
热议问题