什么时候要写分号,什么时候不写分号,一篇文章讲清楚

87 阅读2分钟

为什么有的公司要求代码结束要写“;”,有的公司就不要求写“;”?这也曾经是程序员之间热议的话题。

没有分号

下面是一段没有分号的代码。

展开查看
const suffix = 'node'
['left', 'right'].forEach(item => {
    console.log(`${item}_${suffix}`)
})
    
    

no_semicolon.png

上面这段代码直接是无法运行的,报一个错误:

no_semicolon_error_output.png

将代码放到prettier里转换一下

展开查看
const suffix = 'node'[('left', 'right')].forEach((item) => {
  console.log(`${item}_${suffix}`);
});
    
    

no_semicolon_prettier.png

可以看到js被转换成了下面这段代码,这段代码仍然是无法运行的,会报上面一样的错。

但是可以很清晰的看到,js引擎会将字符串'node'当成数组去取索引为('left', 'right')的值,'node'只能取出['n', 'o', 'd', 'e']这几个值,('left', 'right')会返回'left','node'['left']取一个不存在的所以'left'必然会返回undefined,undefined调用forEach一定会抛出Uncaught TypeError: Cannot read properties of undefined (reading 'forEach')

放到eslint里检测一下

no_semicolon_eslint.png

可以看到eslint检测到第二行第一个字符有异常换行,ESlint检查出了没有分号会导致代码无法运行。

Error 2:1 Unexpected newline between object and [ of property access.  ([no-unexpected-multiline](https://eslint.org/docs/rules/no-unexpected-multiline))
const list = undefined
const temp = 1
(list || ['left', 'right']).forEach(item => {
    console.log(item)
})

有分号

再看看代码结束写了;的情况,下面这段代码添加了分号,可以正常运行。

展开查看
const suffix = 'node';
['left', 'right'].forEach(item => {
    console.log(`${item}_${suffix}`);
})
    
    

prettier格式化也正常。

semicolon_prettier1.png

选择不使用分号进行格式化,prettier补了一个分号进行兼容,代码也可以正常运行。

semicolon_prettier2.png

当然eslint检查语法正常。

生产环境的代码

生产环境的代码进行了加密混淆。但是也可以看到,为了能够正常运行,补充了大量的分号。

vue源码

vue_source.jpg

vue编译后的代码

vue_source1.jpg

发现vue开发团队或许编写代码时不写分号,或者提交代码时使用prettier去除了分号。

编译后的代码也会为了稳定运行,会补充大量的分号,还解决压缩后的一行代码可以安全运行。

他们使用githook搭配prettier、eslint代码进行提交格式化和提交时和开发时检测。 prettier&eslint Dingtalk_20230731185853.jpg

总结

写js时写不写分号,如果是个人项目,遵循自己的风格就可以了。如果是团队开发,就要和vue团队一样,为了风格统一,统一不写分号,或者写分号。

无论是上面哪种情况,都要写好代码风格,使用工具进行检测和格式化。

感谢你看到这里,如果你有什么想法和建议,可以在下面留下你的想法。