Best way to prevent/handle divide by 0 in javascript

后端 未结 8 2007
天命终不由人
天命终不由人 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;
      }
    }
    

提交回复
热议问题