我曾经听说,在一行语句中使用花括号对JavaScript是有害的。我不记得推理了,谷歌搜索也没有多大帮助。

在JavaScript中,把所有语句都用大括号括起来是一个好主意吗?

我这么问,因为似乎每个人都这么做。


当前回答

No, curly braces are not necessary, However, one very important reason to use the curly brace syntax is that, without it, there are several debuggers that will not stop on the line inside the if statement. So it may be difficult to know whether the code inside the if statement ran without altering the code (some kind of logging/output statements). This is particularly a problem when using commas to add multiple lines of execution. Without adding specific logging, it may be difficult to see what actually ran, or where a particular problem is. My advice is to always use curly braces.

其他回答

我想指出的是,你也可以把花括号去掉else。正如约翰·瑞西格在这篇文章中看到的。

if(2 == 1){
    if(1 == 2){
        console.log("We will never get here")
    }
} else 
    console.log("We will get here")

我在一个类似的经历中找到了这个答案,所以我决定用我的经历来回答它。

无括号语句在大多数浏览器中都可以工作,然而,我测试了无括号方法实际上在某些浏览器中不起作用。

截至2018年2月26日,该声明在苍白的月亮,但不是谷歌Chrome。

function foo()
   return bar;

有很多好的答案,所以我不会重复,除了说我的“规则”时,大括号可以省略:条件'返回'或'抛出'(例如)作为他们的唯一声明。在这种情况下,流控制已经清楚地表明它正在终止:

由于终止流控制,即使是“坏情况”也可以快速识别(并修复)。这个概念/结构“规则”也适用于许多语言。

if (x)
    return y;
    always();

当然,这也是为什么人们可能会使用linter..

在一行语句上使用花括号是没有编程理由的。

这只取决于程序员的偏好和可读性。

您的代码不会因此而崩溃。

不直接回答问题,但下面是关于一行中的if条件的简短语法

Ex:

var i=true;
if(i){
  dosomething();
}

可以这样写:

var i=true;
i && dosomething();