Best way to prevent/handle divide by 0 in javascript

后端 未结 8 2010
天命终不由人
天命终不由人 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:03

    A bit different than stopping execution, but the ternary operator is a pretty slick way to customize variable assignment.

    var one = 1,
        zero = 0,
        customValue = 1;
    
    
    var quotient = zero===0 ? customValue : one / zero;
    

    This way, by setting the customVariable to the integer of your choice, you can expect a predictable result when division by zero occurs.

提交回复
热议问题