Putting ; at the end of a function definition

情到浓时终转凉″ 提交于 2019-12-04 23:50:25

TL;DR: Without a semicolon, your function expression can turn into an Immediately Invoked Functional Expression depending on the code that follows it.


Automatic semicolon insertion is a pain. You shouldn't rely on it:

var tony = function () {
   console.log("hello there"); // Hint: this doesn't get executed;
};
(function() {
  /* do nothing */
}());

Versus:

var tony = function () {
   console.log("hello there"); // Hint: this gets executed
}
(function() {
  /* do nothing */
}());

In the second (bad) example, the semicolon doesn't get inserted because the code that follows it can make sense. So the anonymous function you expected to be assigned to tony gets called instantly with some other stuff as argument and tony gets assigned to the return value of what you expected to be tony, which is really not what you wanted.

You posted a function expression. Unlike blocks, statements are terminated with semicolons so you should insert a semicolon there instead of relying on ASI to do it for you implicitly.

Not adding the semicolon can result in unexpected behaviour depending on the code that follows.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!