



























My previous post included this paragraph:
letvsconstvsvar: Usually you wantlet. If you want to forbid assignment to this variable, you can useconst. (Some codebases and coworkers are pedantic and force you to useconstwhen there is only one assignment.)
This turned out to be very controversial, sparking conversations on Twitter and Reddit. It seems that the majority view (or at least, the most vocally expressed view) is that one should use const wherever possible, only falling back to let where necessary, as can be enforced with the prefer-const ESLint rule.
In this post, I will briefly summarize some of the arguments and counter-arguments I’ve encountered, as well as my personal conclusion on this topic.
prefer-constlet and const every time. A rule like “always use const where it works” lets you stop thinking about it and can be enforced by a linter.const gives you confidence you’ll always “see” the same value.const implies immutability. However, one could argue that it’s important to learn the difference between variable mutation and assignment anyway, and preferring const forces you to confront this distinction early on.useState are more like parameters. They flow in one direction. Seeing an error on their assignment helps you learn earlier about the React data flow.const run faster due to the knowledge the variable won’t be reassigned.prefer-constconst everywhere it can work, we lose the ability to communicate whether it was important for something to not be reassigned.const, someone always confuses with immutability. This is unsurprising, as both assignment and mutation use the same = operator. In response, people are usually told that they should “just learn the language”. However, the counter-argument is that if a feature that prevents mostly beginner mistakes is confusing to beginners, it isn’t very helpful. And unfortunately, it doesn’t help prevent mutation mistakes which span across modules and affect everyone.const-first codebase creates a pressure to not use let for conditionally assigned variables. For example, you might write const a = cond ? b : c instead of an if condition, even if both b and c branches are convoluted and giving them explicit names is awkward.var or let. If we insist on speculating, we could just as well speculate that extra checks can create performance cost rather than reduce it. But really, engines are smart.I don’t care.
I would use whatever convention already exists in the codebase.
If you care, use a linter that automates checking and fixing this so that changing let to const doesn’t become a delay in code review.
Finally, remember that linters exist to serve you. If a linter rule annoys you and your team, delete it. It may not be worth it. Learn from your own mistakes.
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。