TE
科技回声
首页24小时热榜最新最佳问答展示工作
GitHubTwitter
首页

科技回声

基于 Next.js 构建的科技新闻平台,提供全球科技新闻和讨论内容。

GitHubTwitter

首页

首页最新最佳问答展示工作

资源链接

HackerNews API原版 HackerNewsNext.js

© 2025 科技回声. 版权所有。

Ask HN: TIL JavaScript switch is weird – why?

3 点作者 mangeletti超过 8 年前
Given the following, what do you think the console output will be?<p><pre><code> var x = 1; switch (x) { case 1: console.log(&#x27;case 1&#x27;); case 2: console.log(&#x27;case 2&#x27;); case 3: console.log(&#x27;case 3&#x27;); default: console.log(&#x27;default&#x27;); } </code></pre> Before you raise your hand, yes I&#x27;ve intentionally omitted the break statements.<p>And, the answer is:<p><pre><code> case 1 case 2 case 3 default </code></pre> The switch is designed to execute every case after the first match, which is the reason for placing a `break` after each case.<p>My assumption was always that the `break` was to avoid wasting the interpreter&#x27;s time on checking the remaining cases when you knew they&#x27;d all be non-matches, not that `break` was basically required.<p>This means that the switch statement itself is basically useless without `break`, unless each case is ordered in a 1[2,[3,[4]]] fashion (I imagine that&#x27;s quite rare).<p>Is this just an artifact taken from C, or is there something else I&#x27;m overlooking?

2 条评论

richardboegli超过 8 年前
Artifact from C. This is by design for consistency. Java does the same.
davelnewton超过 8 年前
This is how switch statements work in a <i>lot</i> of curly-brace languages.<p>Intentional fall-through isn&#x27;t as rare as you seem to think, though--not useless at all.