9 ms·
I'm surprised by the state of const/let nowadays. The well-known good practice: use const by default; use let when it's needed. At the release of ES6, it was t
by ggregoire 10y ago
I'm surprised by the state of const/let nowadays.
The well-known good practice: use const by default; use let when it's needed. At the release of ES6, it was the way to go. But everyday I notice libraries—and some really famous— that use let everywhere in their docs, or some really influent developers from Google or Facebook who share samples of code on Twitter using let when it's not needed [1]. I don't know why. Seems like most people now think that const is for declaring constants (in the traditional meaning, like const API_URL) when it's just the normal way to declare variables that don't need to be reassigned (so basically most variables).
Dan Abramov said: "some people say const is ugly" [2]. Well, if it's a matter of appearance...
[1] https://twitter.com/addyosmani/status/789126892402204673 https://twitter.com/addyosmani/status/789126892402204673
[2] https://twitter.com/dan_abramov/status/783708858803978240 https://twitter.com/dan_abramov/status/783708858803978240
- djur 10y agoIt should have been "let"/"let mut", not "const"/"let" (or some other scheme that makes immutable bindings terser). I recall people warning of this outcome at the time of standardization.
- pmoleri 10y agoI resisted const for like 10 minutes. You get used to it really quickly and then when you see a 'let' in your code you just know something is happening with that variable afterwards. When I have to go back to programming in a language without const declarations it feels bad.
- JoeAltmaier 10y agoI know I should use const. I lazily leave it until the end then try to shoe-horn it in. Then it ripples through the code until I give up. Then I hate myself.
- dsp1234 10y agoI've started to use const for every variable, then if I get an linting error about modifying a const, I switch it to let. It took about two weeks to train my hands/brain to type const before let/var.
- rkwz 10y agoI use https://www.npmjs.com/package/eslint-plugin-const-immutable https://www.npmjs.com/package/eslint-plugin-const-immutable for linting const usage. It even detects object props mutation!
- pauljaworski 10y agoThis is what makes Eslint so great. If you extend Airbnb's (or write your own very strict) config, it will really enforce best practices for things like this. I think running eslint --fix will even change your "let"s to "const"s where appropriate, but don't quote me on that.
- btdiehr 10y ago--fix is a godsend.
- rkwz 10y ago>I think running eslint --fix will even change your "let"s to "const"s where appropriate, but don't quote me on that. Yep, this is the relevant rule - http://eslint.org/docs/rules/no-var http://eslint.org/docs/rules/no-var Though it just replaces all var with let. I expected it to intelligently use either const or let depending on how the variable is used ¯\_(ツ)_/¯
- WorldMaker 10y agoIt also doesn't help that let is 3 letters versus const is 5; programmers if anything will default to the faster to type option.
- mort96 10y agoThis. I personally agree with everyone saying const > let, but I just don't find myself caring enough about it to add the inconvenience of typing 5 characters instead of 3 every time I need to create a variable.
- oldmanjay 10y agoYou'd think after all these decades I'd no longer be surprised that programmers try so hard to minimize their typing, since it has no demonstrable positive impact on code quality. I guess premature optimization is in the blood of some people.
- z3t4 10y agoThe right path have to add more value then the path of least residence.
- mort96 10y agoIt's not about working hard to minimize typing, it's more about not wanting to switch from a state of little typing to a state of more typing. Also, it has nothing to do with optimization; I don't think there exists a single person who uses "let" over "const" because of performance reasons. I also don't think anyone uses "let" over "const" because they think it improves code quality.
- singularity2001 10y agoTrue, which is why we drop any var/let/const for prototyping
- riquito 10y agoIt doesn't help that many variables are objects, and const means that you cannot reassign the variable, not that you cannot modify it. e.g. const x = {}; x.foo = 'it works!'
- ggregoire 10y agoMaybe in ES9 we will have immut x = {}; x.foo = 'it doesn't work! :)' At the moment, we can use these libs to achieve it - https://github.com/rtfeldman/seamless-immutable https://github.com/rtfeldman/seamless-immutable - https://github.com/facebook/immutable-js https://github.com/facebook/immutable-js
- BinaryIdiot 10y agoWe don't need any libraries to solve this issue (please don't bring in libraries to do weird stuff like this; that's a dependency that you'll be stuck with forever over your entire codebase for essentially zero reason IMO). Just use `const` + `Object.freeze()`; it'll get you 99.9995% of exactly what you want.
- RussianCow 10y agoI'll give you two reasons: performance and ease of use. When you need a copy of a large object with a small change, performing the copy with native JS is going to be slower than doing it with a specialized data structure like a hash mapped trie[0] (which is what Immutable.js uses). Also, if you're trying to keep your data truly immutable, that copy operation is going to be a pain to write with the built-in tools, whereas it's super easy to return a copy of an object with a change to a single, deeply nested property with Immutable.js. I agree that it's premature to reach for a library before you need it, but let's not pretend there aren't rather large drawbacks to using Object.freeze and Object.assign. [0]: https://en.wikipedia.org/wiki/Hash_array_mapped_trie https://en.wikipedia.org/wiki/Hash_array_mapped_trie
- BinaryIdiot 10y ago
- cloakandswagger 10y agoIs it just me, or is Javascript (and more generally, all front end technology) more susceptible to these trivial holy wars? While I agree that const/let is a useful convention for communicating mutability, it isn't nearly a big enough deal to warrant the attention it receives from the community. It's not just const/let; I rarely make a front end PR that isn't bike-shedded to death over subjective styling choices, single quotes vs double quotes, etc. It often feels like conforming to flavor-of-the-week, subjective decrees from frontend trendsetters is more important than the substantive work that your code is doing.
- abritinthebay 10y ago> Is it just me, or is Javascript (and more generally, all front end technology) more susceptible to these trivial holy wars? - Tabs vs spaces. - Vi vs Emacs - Weak vs strong typing - where to place {} in block statements - where to put commas No, programming in general is susceptible to these trivial holy wars.
- nothrabannosir 10y agoWeak vs strong typing is hardly "trivial"... it's the very foundation of a language. Not trying to derail the convo or take sides, but one of these is not like the others ;)
- nitroll 10y agoHardly anyone argues weak vs. strong types, the battle is primarily between dynamic vs static typing.
- gotofritz 10y agoVi vs Emancs? Weak vs strong typing?? tabs vs spaces??? where did you get those?? The ONLY holy war in JS is the semi-colon one
- lmkg 10y ago
- irrational 10y agoI wish they had come up with something else than "const". I can't not see it as anything other than "the traditional meaning like const API_URL". Those writing the spec should have forseen this and used something else. I suspect that this is something like arrow functions. The concept of arrow functions is great, but using something that looks like "equal to or greater than" was poor judgement. I know that this was taken from other programming languages and I can't help but suspect that using const to mean something other than it's tradition meaning is something borrowed from some other language.
- RussianCow 10y agoIt also doesn't help that in Swift, 'let' is equivalent to JavaScript's 'const', so if you write code using both languages, it's easy to forget that and just use 'let' everywhere.
- strainer 10y agoThe only difference between const and let is it flags an error on reassignment (in strict mode), so that is its primary purpose. It can also be used to conspicuously note intent not to reassign but it is not helpful to VMs or programmers to explicate whether or not each and every variable is reassignable. Maybe just get on board with those influential developers and use const to lock things down (in strict mode) or to make a point - not because let is 'not needed'. I would rather const was used somewhat sparingly, giving it narrative impact.
- deleted 10y ago[deleted]
- Hurtak 10y agoI heard interesting argument against const, it went like this: Const very rarely saves you from bugs and the bugs that saves you from are very easy to find and fix. On the other hand the time wasted by thinking where whether to write const or let and the time wasted by switching consts for lets (and other way around) outweighs the time saved by potentially preventing these easy to find bugs. To sum it up, if consts does not really provide any extra value, why not make your life easier and just use let everywhere. It was from very senior c++ programmer, so I am not sure how well that translates to JavaScript.
- skrebbel 10y agoThat makes a lot of sense for c++ constness, which has virtually nothing to do with JavaScript's const. C++ constness is significantly more far-reaching and therefore more work to get right. I agree with his position. JavaScript const is just a matter of typing 2 more characters and in exchange you make your code more readable (because you communicate "this stuff will never change from here on", which makes understanding the stuff that does mutate easier). There are no far-reaching consequences. Just type "const" everywhere.
- rkwz 10y ago> C++ constness is significantly more far-reaching and therefore more work to get right. I'm not familiar with C++, can you explain more?
- skrebbel 10y agoA const variable means that variable won't change. So `const int i = 6` means i will never change. But often you'll use pointers or references, these are C++'s way for a variable to point to data elsewhere. You can also make the pointers or references themselves const. Finally, you can make functions const too, which lets you turn C++ into half a haskell. First pointers and references. For simplicitly I'm going to ignore references and focus on pointers - the difference is not very interesting in this context. In most languages you probably know, referring to objects is done implicitly: variables that "are" objects are actually references to objects located elsewhere, and variables that are primitive types (numbers, booleans, strings) are just right there. Because of this, in JavaScript you can do this: var a = {}; var b = a; b.moo = 6; a.moo === 6; // true In here, a and b point to some object that "is" neither a or b - the object itself just floats around in memory and it'll exist until neither a, b, nor anyone else points to it anymore and the GC decides it has to go. In C++, you'll need pointers or references for this, eg. somestruct a; somestruct* b = &a; //b now points to a a.moo = 6; b->moo == 6; // true (-> is just C++ shorthand for "follow the pointer and then do a property lookup). Ok now const. somestruct const a; a.moo = 6; // error! can't modify a const. Ok well how about somestruct a; somestruct* const b = &a; b->moo = 6; a.moo === 6; // true This means the pointer is const. That works because we never change where b is pointing to. So how about: somestruct a; somestruct const* const b = &a; b->moo = 6; a.moo === 6; // true Oh damn. Crying baby. Const functions will have to wait for some other day.
- millstone 10y agoHow do you feel about `const` for variables that are not reassigned but are still mutated? const array = [1, 2, 3]; array.push(100); // unexpected? I prefer to use let for bindings to objects that get mutated, even if the variable is not re-bound.
- madamelic 10y agoYeah, I wrestled with that briefly. For anyone not in the know, declaring `const` on an object only makes it where you can't re-assign the object, but you can still mutate its 'members'. Personally, I use `let` just to symbolize that it isn't a constant and does change even though I could declare it a `const`. I think it makes the code more readable.
- btown 10y agoAs far as I know, the "correct" approach is to act as if every object is deeply frozen (perhaps actively testing using Object.freeze... IMO https://github.com/ecomfe/babel-plugin-freeze-const https://github.com/ecomfe/babel-plugin-freeze-const has the right idea but is nothing more than an idea), and transform things into new objects functionally, using .map and friends. The problem is that, while a lot of things can be expressed elegantly this way, sometimes the most maintainable thing, or the most efficient thing, is to have some side effects in a deep loop in a certain algorithm, and it's very difficult to do this with purely functional JS. The real solution is to allow your const bindings to be mutated when you need to, and comment explicitly to make things perfectly clear!
- deleted 10y ago[deleted]
- caub 10y agoit's sad the longest of [var, let, const] is the most useful one. They should have made let behave like const