is switch(true) {… valid javascript?

后端 未结 5 1789
暗喜
暗喜 2020-12-31 00:59

I recently came across code where a switch statement seemed reversed with the answer (boolean) in the switch and the expressions in the case. The code ran fine as intended b

5条回答
  •  自闭症患者
    2020-12-31 01:27

    Yes, it's valid.

    As in many "modern" languages, the switch in Javascript is very far from the original int-based switch from the C language, it only keeps the general semantics.

    The switch clause, as normalized in ECMAScript, is explained here in details : http://www.ecma-international.org/ecma-262/5.1/#sec-12.11

    Basically, the first case whose value is equal to the expression in switch(Expression) is executed.

    The main advantage over the obvious if else if sequence is the ability to ommit the break statement and execute more than one block. Note that, contrary to the old C switch, there is no real performance improvement and in this case it's neither more succinct nor more readable.

提交回复
热议问题