r/javascript • u/bornforcode • Apr 01 '18
Google publishes a JavaScript style guide. Here are some key lessons.
https://medium.freecodecamp.org/google-publishes-a-javascript-style-guide-here-are-some-key-lessons-1810b8ad050b
714
Upvotes
2
u/[deleted] Apr 02 '18 edited Apr 02 '18
I've said nothing about
var.Be honest: when was the last time your starting point to reading / changing code was "I need to consider which one of these local variables I could reassign"? Has that ever happened to you?
This decision what to reassign doesn't flow from how the variable was declared. It flows from what you want the function to do in the end. If you need to reassign a
constvariable, you wouldn't even skip a beat, you'd go changeconsttolet. You wouldn't treat pre-existing declarations as eternal and unalterable. Heck, most times when refactoring a local function, many of the pre-existing variables might not even survive the edit at all.What matters is what you want the code to do, not how it happened to be factored the first time around. And if you're honest, you'd agree with that.
It's very easy to come up with artificial scenarios where
constis helpful. They may even pass as logical in a Reddit comment. But if they make no sense while you're coding, if they rarely if ever happen in the real world, you're basically lying to yourself.And you may consider this a superficial concern, but if
constis to be a default choice for local variables then it has the worst name ever. A constant is not a variable. It's the opposite of a variable. A variable "varies", and constant is "constant". We're doing this because we like math and functional programming, right? In math and functional programming, a variable is not reassignable, but it can vary on each function run. A constantly is universal. Like Pi, or E. Pi doesn't change depending on your app runtime state. A constant shouldn't depend on runtime state, it shouldn't be mutable. It makes it a not-constant. It makes it a variable.When the goal is "make code readable", this is relevant. Words have meanings. When I'm skimming through post nine thousand about how "JS const is not about constants" I don't think "wow I'm so glad I know this, this is opening new doors to me, everything can be const". No, I think "ECMA fucked up".