How is the ternary operator evaluated in JavaScript?

前端 未结 4 1099
猫巷女王i
猫巷女王i 2021-02-19 06:19

Regarding the ternary (? :) operator in JavaScript, I would like to know how it is evaluated by a typical browser\'s JavaScript interpreter:

Alternative A:<

4条回答
  •  渐次进展
    2021-02-19 06:23

    The ternary operator evaluates lazily for several reasons.

    1. It's inefficient to evaluate all the operands when you are only going to return either the if or the else
    2. Doing lazy evaluation allows you to do things like x != 0 ? 10 / x : 10; If it evaluated everything at the same time you would get a divide by zero error if x were zero

提交回复
热议问题