Does JavaScript have “Short-circuit” evaluation?

前端 未结 3 820
温柔的废话
温柔的废话 2020-11-22 12:04

I would like to know if JavaScript has \"short-circuit\" evaluation like && Operator in C#. If not, I would like to know if there is a workaround that makes sense to

3条回答
  •  星月不相逢
    2020-11-22 13:02

    The idea is that logical expressions are read left-to-right, and if the value of the left condition is enough to get the total value, the right condition will not be processed and evaluated. Some very simple examples:

    console.log (1 === 1 || confirm("Press OK or Cancel"));
    console.log (1 === 2 && confirm("Press OK or Cancel"));
    
    console.log (1 === 2 || confirm("Press OK or Cancel"));
    console.log (1 === 1 && confirm("Press OK or Cancel"));
    console.log (confirm("Press OK or Cancel") || 1 === 1);
    console.log (confirm("Press OK or Cancel") && 1 === 2);
    

    The first two expressions above will print to console results true and false respectively and you will not even see the modal window asking you to press "OK" or "Cancel", because the left condition is sufficient to define the total result.

    On the contrary, with the next four expressions, you will see the modal window asking for your choice, because the former two depend on the right part (that is your choice), and the latter two — regardless of the fact that the result does not depend on your choice — because left conditions are read first. So, it is important to place conditions left-to-right based on which ones you want to be processed first.

提交回复
热议问题