No const! How NOT To Give A JavaScript Talk
Вставка
- Опубліковано 25 чер 2024
- Let's talk a look at Ryan Florence's Epic Web Dev talk "Let Me Be" where he wants to convince us to use a lot more "let" in our JavaScript and a lot less const. Does he do a job convincing us? Are you convinced? And if you are do you think you could defend that position to your coworkers? And what can we learn for our own presentations? Let's find out!
Let Me Be talk: www.epicweb.dev/talks/let-me-be
00:00 Introduction
00:49 A Whole Mess Of Tweets
03:00 The AirBnB Anecdote
04:03 Language Is Hard
05:00 Finally Some Code
07:05 ChatGPT FTW
08:20 Const Hurts Your Mouth
09:00 What Have We Learned - Наука та технологія
I can see Ryan's point that using `const` by itself doesn't matter. However, `const` shines because using it by default makes `let` stick out like a sore thumb. It's an extremely valuable visual hint that "this is doing something unusual, pay more attention to it". If you use `let` everywhere, you lose that "here be dragons" helper.
Very well said
Yep, agreed 💯
100% this.
I always use const until I need let. And that makes my intent more explicit in my code when something is intended to be reassigned. I still use const + SCREAMING_CASE for actual constants. Most importantly, when I talk about the code, I refer to const CONSTs as 'constants' and const + let as 'variables', regardless of what the ES6 name is. I don't call variables 'lets' for example. Not sure why Ryan can't distinguish between what they do and what JS uses for declaration names. Pythonistas still remember to call them variables even without any var/let/const/int..
It's a good point, but for some reason we've flipped "if everything is important nothing is" on its head for the sake of "not accidentally mutating variables". Should it not be const for the important stuff and let for everything else?
Totally agree.
I like how fluently and, seemingly, without any effort you keep yourself from calling that talk a total bullshit under the blue moon, which it definitely is. Respect :)
I'm not here to do that honestly. I just want to teach folks how to do web stuff. This video is way outside my wheelhouse. I only covered it because enough folks were taking it seriously that I had to say something. If the video were marked as parody up front I wouldn't have said anything. Though as parody goes it didn't really do it for me either.
@@jherr Yeah, I watched the original, and to me it screams parody/joke lecture. I'm pretty sure his only actual point is he prefers to reserve the "const" keyword for constants and not use it for variables that happens to not be reassigned (which is a valid preference, though I have the opposite preference) and the rest of the "arguments" were just joke arguments probably delivered too deadpan for everyone to notice. It feels like neurodivergent humor, we often enjoy making up silly arguments to justify a preference which really is just a preference.
When you have years of experience in programming, you realise that most "rules" in programming is just preferences so this lecture would be an obvious joke for most veterans, and judging by the laughter I assume most of the live audience were experienced programmers who correctly interpreted it as a joke lecture too (it feels like a slightly off topic, lighthearted lecture that is often scheduled last at a conference as entertainment after a long day of hard topics); but either he or whoever uploaded it to the internet forgot that it might not read as such an obvious joke to a general audience when removed from the context.
I've seen other developers, smart developers, use let instead of const when they should have used the former, and as over thinking and analytical as I am, I always wondered why they'd do it that way.
While I never got an actual answer, I think it was just because it's easier and very slightly quicker to type for some people, being one character shorter. But even then, it's just a guess.
Now, I could maybe see an argument if it causes an issue with memory usage or garbage collection, but, again, that's just a theory.
As for me, I use it everywhere. I only use let if I absolutely need it.
Coming previously from the world of C++, const is perfectly fine to me.
When declaring primitive type values as const, then they are constants. End of story.
When declaring a value of a complex type to be const, then I understand it as "the reference to the content in memory for this object is const", that is "the room number is const, the contents of the room itself are not".
Again, no problem with that either.
Totally agree, it's like "int* const i = &x;" IOW: 'i` itself cannot be re-assigned, but what `i` is pointing at `x` can. *i = 42 In this sense it's no different to how JS handles Objects, objects in JS are implicitly pointer types, it's just more automatic.
Note that values of complex types can indeed be const, not only pointers e.g. const Dog fido;
You can also have const pointers as you describe, or pointers to const (where the pointed-to type can either be const or not)
This is what I was thinking too. The whole talk is basically just another medium article with a title "Stop using / doing X" and you just know because all reasoning is suspiciously absent. If you think you complex types aren't constants, declare an array and try to change it to a primitive. I guarantee you it won't work.
coming from c++ too most useful thing I foumd about them is when passing in an array to a function and setting it to const if it is meant to be read only ensuring the contents are not changed by the function. I guess this is different in javascript as the address is unaltered but the contents of the array can be changed by the function.
And the root type is constant as well. A let variable can change from any complex type into any other type at any point. Consts stay their assigned type forever.
ChatGPT also spelled "their" wrong in its response... I think we can all take that accident to its logical conclusion.
touché
Yes and relying on ChatGPT for that kind of advice is probably unwise anyway. ChatGPT can answer tons of questions about it's training data and even extrapolate from there. But to assume that the training data is mostly correct is quite a leap. Collect information, form your own opinions.
@bertilorickardspelar ChatGPT is a tool, but it states possibilities with certainty. Same as most other LLMs. It can hallucinate... ask it to write you some Javascript to make a request to AWS S3 that will make you cheese on toast. It will do it.
Used as a tool, it can be great to turn words into structure. If you are stuck on loops within loops and struggling to turn your verbalisation/pseudo into actual, it can be very useful.
@@bertilorickardspelarI think you missed the point of what the misspelling implies.
@@grahampcharles I assumed it meant that it was written by a human and not AI. I think the lecturer tried to fool the audience that his point was valid because an AI agreed with him which it did not. I agree with Jack. Const is not a magic bullet but it will not ruin your code either.
The biggest danger with AI is trusting it too much.
I don’t see the problem with const = array[]. It’s a pointer to an array, that pointer never changes.
It would be preferable though if a const array contents were immutable though.
Yeah in JS I'd say it's a good practice to use const only for an array you don't want to change. While JS will allow you to alter the object, it can get confusing given JS doesn't have an explicit distinction between pointers and the objects they point to being const in the way that C does.
@@mistymu8154 Why? const indicates that the identifier binding never changes. It means nothing about mutability. I use const for values I intend to mutate all the time. I have yet to hear an argument about why this is bad. const is for binding, freeze is for immutability.
@@mistymu8154 This is how it is in every language though. The const signifies that the reference won't change. If you want an immutable data type, then you use an immutable data type. You'll notice he didn't use any examples with strings because they are immutable.
Not in Rust. In Rust you can only use .push on a Vec that is mutable
I'm in the const camp as well. And I like using linting rules which push for const if no reassignment happens. This way, seeing a let is an indicator for me that there is reassignment to watch out for. As of arrays/objects defined via const: We all know that const doesn't prevent their content to change. But at least they will remain the same type. It's the same with TypeScript in general: You don't get 100% type safety, but you get at least some level of security. His argument would render TS irrelevant because you can't be sure if there is any any in the code, so "just stick with JS"
I've been learning go recently because I'm tired of TS fake type safety.
I keep going back and forth on this to be honest. I've gotten into a habbit of just writing const, and then letting eslint catch when its being changed to then change it to let. But I do find that the scoping parts of javascript sometims make me wonder why we put so much inside a given function.
@@VeretaxCould you expand on your last sentence?
In JavaScript, using const indicates that the variable will not be reassigned, meaning you're always working with the same object. This is incredibly helpful as it eliminates the need to scan the entire source file or function to check if the object has been reassigned. Remember, you can declare an object with const in a function, mutate it, and return it-the function is still pure because the function isn't mutating data outside the scope of the function. Additionally, mutating an object can be faster than attempting to destructure it into an entirely new object with new memory allocations.
>> "In JavaScript, using const indicates that the variable will not be reassigned"
>>" always working with the same object"
Actually it is not. It can be reassigned. But it cannot be directly reassigned. It will be reassigned many times if you use it inside a for-loop. And yes, it also can hold different objects (or even can hold both objects and other types): for (const obj of [{}, {}, {}, 123, "my string", new Date]) {console.log(obj)}
@@astronavigatorpirx26 When you're using it inside a for...of loop, you don't reassign, you re-declare the constant and then assign a new value to a completely new constant in memory.
@@gownerjones What about using let in cycles then? Do I declare a new variable every iteration? Like in for (let x=0; x
@@astronavigatorpirx26 I'm sorry, I don't know what you want me to tell you. When you use a for..of loop in Javascript, every iteration creates a new instance of that variable or constant. It doesn't matter if you use const, let or even var in this case. All you need to do is type into Google "js why can you use const in a loop" and you'll find this answer readily. It's also described in the official docs in the for..of article:
"You can use const to declare the variable as long as it's not reassigned within the loop body (it can change between iterations, because those are two separate variables)."
And later:
"Note: Each iteration creates a new variable. Reassigning the variable inside the loop body does not affect the original value in the iterable (an array, in this case)."
For...of loops do not reassign the iterating variable or constant by design. That's the reason why we can use const here but not in a normal for loop.
@@astronavigatorpirx26 I understand the confusion I think. For loops and for..of loops work differently. You cannot declare a constant in a for loop. That's because a normal for loop will reassign the iterating variable. But when you use a for..of loop in Javascript, every iteration creates a new instance of that variable or constant. It doesn't matter if you use const, let or even var in this case. This is described in the official docs in the for..of article:
"You can use const to declare the variable as long as it's not reassigned within the loop body (it can change between iterations, because those are two separate variables)."
And later:
"Note: Each iteration creates a new variable. Reassigning the variable inside the loop body does not affect the original value in the iterable (an array, in this case)."
For...of loops do not reassign the iterating variable or constant by design. That's the reason why we can use const here but not in a normal for loop.
Always use const unless you need your variable to actually vary
I've quit a new job (one i just joined) because we hired a new guy that removed consts everywhere and removed native map for lodash map.
I asked for a justification in his PR and he yelled and screamed to the head. I gave my reasons in the PR and I don't think he thought he needed to.
I realized this isn't a place I wanted to work.
yikes! replacing native maps with lodash's would've drove me nuts lol
You assume the risk to go to another company is a huge award for you.
I see the big techs are pushing to do the same bullshit and assume it is the right way to do that.
And this is why almost all the people that work for those companies never change their mindsets.
Did anyone approve the PR? Did anyone take your position?
I am convinced that the talk was a meme 🤣
It was. I thought the fabricated ChatGPT was a dead giveaway 😆
@@KentCDodds-vids 💯and I'm sure he got us good 😅
@@KentCDodds-vidsOops! I've already gone ahead and updated all production codebases to utilize 'let'. My bad! :(
I mean Ryan is sincere in his preference, but he really doesn't care what other people are using and doesn't need everyone to stop using const. He really just wanted to have a place he could direct people to when they ask him why he prefers to not use const. And he did so in the light hearted way he does things.
@KentCDodds-vids but then you're saying that it's not satirical. You kinda can't have it both ways. You can't say it's satire and then turn around and say that it's actually a genuine resource for his position, but if you poke holes in then hide behind satire.
JavaScript community just running out of stuff to do conf talks about at this point
This is how reaction content should be. Well done sir.
Brilliant! That’s exactly how everyone should consume information critically. Not just in tech but with regard to everything.
The misspelling in the "ChatGPT response", LOL.
at 8:08 , i have never seen chatgpt spell their as thier before.
I saw that too. That was definitely a fake GPT response.
Good catch.
hawkeye
Using ChatGPT, that constantly makes up shit as a source of truth for your argument is just yikes. Imagine if that became the standard for all coding practices we rely on. "The AI told me to do it this way!"
We will have spaghetti code in few years, many people rely a lot in AI tools that don't even stop to read or think what the output actually is, just copy paste and done, quite disturbing in my opinion.
Not to mention that the chatgpt quote was obviously faked.
@@amaury_permer So true, everyone reduced to script kiddies just copy pasting unreadable mess generated by AI. All human skill gone. I dont want that future! Sure use AI for help is ok sometimes, I do that myslef alongside Stackoverflow but I always only use it only as a template. I never downright just copy paste it into my projects as it is and certainley not without myself understanding what the code is really doing.
Yes, misspelling "their" is the last thing an LLM would do, unless you asked it to, and possibly included to indicate that portions of the talk are for entertainment purposes only
@@JR-jx5ymLLMs make grammar and spelling mistakes from time to time
Reminds me of the time a coworker said we should always nest ternaries and cited a Medium article to back it up.
Should've cited "Structure and Interpretation of Computer Programs, JavaScript Edition" book, it's full of them.
Ha! Many linter configs actually warn against doing these. :)
Ugh, I did one today, and wanted to take a shower afterward. But it lead me to encapsulate logic into two separate components rather than do it all in one place.
@@Veretax If you 💭 it should be a separate component, it probably should be!
@@codefinity I mentioned this example because it was fresh in my head I didn't set out to have separate components but then I realized I had so much different logic that would make sense to separate those different ways of rendering into two components
The ChatGPT response on the slide has a typo. `thier` instead of `their` GPT doesn't make spelling mistakes like this. He made it up.
No he didn't. I put the same prompt into ChatGPT and got a very similar long-form response clearly advocating for the use of const. You can easily verify this yourself.
He was talking about the original "ChatGPT" quote the guy used to support NOT using const. Not the ChatGPT screenshots the video poster shows where he tested it himself clearly showing, exactly as you say, long form response clearly advocating for the use of const and showing the first screenshot to be complete bs.
Ryan is an awesome developer, it's needless to say it. Honestly, that talk sounded like "we need 5 min of anything to fulfill a slot in the conference". To make it more useful he could've mentioned how the typescript's `` const... as const` fixes the single case where const is misleading (not useless) he presented. In general, IMO, const makes code much easier to read.
When Ryan says that AirBnB is not using their own lint rules, I don't think it's necessarily an appeal to authority fallacy. It could be in response to another appeal to authority - that you SHOULD use airbnb lint rules because they created it.
You are correct, more precisely it's an anecdotal fallacy.
@@jherr yes, I think that was the only weak point in your perfect and super clear explanation. The mention to airbnb folks not using their own stuff was to discredit the the airbnb lint rules themselves
what a GREAT analysis!!! definitely love the critical approach, this is also the kind of thinking we need to use for code reviews
Ooh this got to be one of your best videos. To often devs take whatever reputable people say as gospel. You have guys touring the world trying to share (sell) their opinion to the industry. Sometimes they bring good insight. But likewise they can bring devs to making decisions that are costly.
ChatGPT would not make a typo in "their"...
Same feeling Jack, I saw that talk and I said to myself, "this can't be happening." I really don't understand the need for this. So much to talk about or contribute or at least try to want to facilitate, let's say learning. But does this man really go out with this?
I think that some of those tech gurus' inflated egos sometimes get over their logical reasoning and they end up shouting sweeping statements like this one. There isn't even a bit of reasoning in this talk, just a statement. Personally I use const whenever I can for several reasons, the main one being the possibility of accidentally change a variable when you're not supposed to.
Constant allows for you to mutate the data, but the object type doesn't change. It helps skip certain steps with interpretation.
Thanks for the video! You speak with much reason as usual that's what I liked the most, I have heard in the last few days some people repeating the same argument about const and I really was not convinced at all!
I will keep using const in specific cases it's always helpful
When I read the title for the video I thought for a while that JavaScript had a hidden flaw that no body knew for all that time and the humanity figured it out just now! 😅
Thanks for raising this issue. There are too many conference speakers popping up who make bold statements like these. It seems like anyone can speak publicly about programming nowadays. Engineers aren't dumb and won't follow advice like this.
Totally agree that, stepping back and re-thinking is the most needed skill for the people in general and not only for developers.
Learn how to think, not what to think is a valuable skill in SE. Great video, mate.
3:55 OMG YES THE COOL KIDS ARGUMENT. I feel like 90% web dev opinions are just cool kids arguments. I've definitely fallen into that as a younger dev. Everything from which editor, language, and let vs const. With this debate in particular, I know const aren't truly constant but I still like the idea of telling another developer that this shouldn't be changed. Kinda like a comment without commenting.
I like your summary, its about developing critical skills and being able to form opinions and 'smell' when its not right. I think your video is talking about where I am trying to get to now, its taken a few years of coding to be confident enough to trust my opinion, whilst I build my baseline. So thank you.
I think, that actually the ability to mutate const value is a very strong argument. I use const a lot, but to be honest I always see a code smell when looking at const in cycles (where const is not const at all), and when constant object are being mutated. The REAL const is just a simple value which can be calculated one time before program started, and does not change every time you run your code (until you change your source code). For such values programmers often use UPPER CASE. like const MY_CONSTANT = 123. (I believe Ryan is talking about this case). You should always be able to replace your real constants (while building project) with real values. If not, then it's not a constant.
Anyway, const keyword in javascript is still useful. Maybe it would be proper to rename it to something like "partially immutable" or "not directly re-assignable" not to confuse programmers. But it's too long, so keyword "const" for such variables is somewhat acceptable.
Great video Jack! I think there are lots of opinions which people follow like rules, especially when they come from places like YT and when targeting easily affected audience. I think we need more content like this video!
This makes me want to do a talk on the value of "const". I find the value of "const" is readability. If I see a function start with "const username = email.split("@")[0];" I know that the value of "username" will be the result of this expression everywhere in the function. If I see "let username = email.split("@")[0];" I need to check throughout the function to see if "username" is reassigned anywhere, and if the codebase enforces "const" where possible then I know that "username" is being reassigned somewhere. If I'm debugging an issue that involves the value of "username" this will be useful information to know.
Great video, I was waiting for a part which you share how typescript fixed this using as const and Readonly array
I appreciate your logical approach to analyzing these opinions! Const makes it very easy for developers to know what can and what cannot be changed. I love that it exists in the language, even if it can still be confusing with reference types for those not as familiar with the underlying workings. But even with that "strageness" around reference types, I find const to be very useful as a reminder to not try to change the particular value. And as Theo and others have pointed out, it brings a lot more meaning to `let` as well, which is a huge bonus and maybe the most important thing about `const`!
Thank you for bringing this up. I definitely need to be a little more critical myself.
I think there is a meaningful distinction between "happens to not be reassigned" and "is fundamentally intended not to be reassigned / other code relies on this never being reassigned".
It would not be unreasonable to adopt a convention where "let" and "const" are used to distinguish between these two cases, because "const" would then convey more meaning about the intent of the code.
For me the only convincing argument for "let" over "const" would just be simplification. "let" would allow for one-time assignments (which I think is a good pattern to default to) and the less common case (at least in the code I write day to day) of having to re-assign multiple times within a loop. Granted you will have to enforce the "one-time" assignment via lint or compiler (which is probably better than discovering violations at runtime).
I could see for a newcomer it being confusing why you would use "const" sometimes but "let" other times. Also you have to understand "const" just enforces a "one time assignment" it has nothing at all to do with immutability.
But at least I'll just use "const" cause its what I have been using and what most others will understand whom I have the pleasure of coding with.
This is like my regular doom scrolling combined with career doom scrolling content all combined into a 10minute delight
I watched the talk before and it really felt like he’s joking but not at the same time, kinda awkward.
my conclusion back then and now are the same, to keep using const unless I have to re-assign to my variable.. but I still loved listening to your critical review of the talk 👌🏼
Yeah, we’re in a STEM field. If a speaker wants to teach me something they should follow the process: state the hypothesis and tests to support, show examples, let us decide if it holds water and we want to consider it theory.
You make great points in this video. He did not start with a clear message/lesson/hypothesis. His examples were not really testing the hypothesis itself, but rather picked after-the-fact to support the vague proposition.
There is a word for this: pseudoscience.
It’s totally fine to have an opinion, but pretty lame for a speaker to present in a way that really doesn’t hold water.
Let's go, Jack! Speaking truth to power here. Love it.
Sir, excellent video. Great content as always
I often feel that conferences are just a "CONSTANT" cycle of repeated opinions and product promotion.
This is good. Your tone and reasoning is very easy to understand too. He should listen to you honestly mwehehe
Thanks Jack for this video and clearing this up! I was half questioning whether he was really serious or not and I do not know Ryan personally but this talk failed on giving the impression that it was satirical.
It was only when he spoke about the sound of const being hard, that made it look satirical
Lets (!) use Vue 3 (same thing applied to react) for exemple: if you do
let something = ref("")
if by any mistake you do something like
something = 'hey';
I wont get an error ... and will loose all further reactivity because the const does not refer to the "not mutability", but to the "reference" to the "proxy object" which you'll loose by reassignement
but if you use const as a default, the linter, the LSP and the JS engine will scream at you. When you try to reassign something you can decide if it was a mistake or if you need a "let". Make sure your system is only moving in ways intended to... that is true in programming and a lot of thing like mechanics and anatomy
What I walked away with from the original talk was not "don't use it" but "don't worry about it so much". I'll use const for things I don't plan to reassign, but when refactoring old code using var it is safe to just find/replace with let and pepper in some consts when it is clear that they won't/shouldn't be reassigned.
For me, the value (hawr hawr) of const is that when I search for an assignment statement, I can immediately stop the search when I encounter a const keyword, because a const can only be assigned once.
Even in loops, with const, the name takes a value exactly once. It is really useful to know and to minimize the number of times the meaning of a name changes.
There are other good ideas here too, such as using Application Programming Interfaces which support the required operations. Some variables are only queried, not mutated.
Who would give up a chance to politely indicate these things to the next programmer? Some techniques incur a higher cost than others.
There are many tradeoffs to make, but IMHO const is worth it's weight in gold.
We can use let and const to indicate that a variable will or won't be reassigned, so we should do that as it adds context for other maintainers. We can also use freeze to indicate that an object will not be mutated, which adds context for other maintainers, but nobody does it because it's a few extra key presses.
Hey Jack,
Really impressive video, especially in the developer world! You did an amazing job of calling out the fallacies in that talk. The "nirvana fallacy" or the idea of a "perfect solution" is definitely one of the most annoying ones. It feels like it goes beyond just forgetting the daily reality of a developer: often the best solution is the pragmatic one, not the perfect one.
A little caveat : while calling out misleading discourse is important, it doesn't necessarily provide a solution to the problem itself. This could still be true for other reasons, or by accident.
This is a great topic for another video! I'd love to hear your thoughts on when using const makes sense and the trade-offs involved.
Love what you do, keep up the good work!
I didn't want it to go long. In short, I always use const, rarely if ever use let, and never use var because of hoisting. My reasoning is that I want to use every feature the language affords to write more robust and reliable code. And so I'm always going to be going for something that offers more guarantees (i.e. const) over let.
A simple example would be this `const [count, setCount] = useState(1);` If I attempt to do `count++` I'm going to get an error because the count is const. But if I use `let [count, setCount] = useState(1);` then I can make that mistake. And I consider the const error to be an early warning sign that I'm doing something wrong. Not that I would make that particular mistake now, but starting out I surely did.
If at the end of the talk you are still unsure if someone is trolling or not, I think it’s safe to say they did not do a good job making their case
5:19 Jack, you misunderstood Yahooda's tweet. He says that const should be used for constants only. The screaming case is an additional semantic hint.
lucky the girl being Jack's daughter as her dad surely showed her something great : how to reason.
Kudos, man. Well done.
btw, about const, for those of us who played with other langages, we know that an object is a pointer, a ref to the object. So making the var (the ref to the object) a const means we locked our ref. but that doesn't mean the object props are locked.
This is, I suppose, why we aren't that suprised by this. But for someone who learn to program with python or js, I reckon that is a tad puzzling.
Your talk convinced me to be not convinced from Ryan's video :D
At least JavaScript devs will never run out of things to argue about
the argument that you can mutate an object which the const is referencing while being the only half serious one doesn't really make sense either , const means that the reference will stay the same for its lifetime, not that the value its pointing to will remain unchanged
I just recently went to a talk about input validation practices that suggested using a 2 state enum instead of a boolean... Sounded like a great way to cause type pollution IMO.
I think their justification was to prevent oneself from passing in a boolean value into the incorrect argument position (ex: when 2 parameters of the same type are adjacent).
Using const is a good idea, first, it gives you some measure of protection against mistakes, second it highlights variables that are mutable so readers of the code can better keep track of them and lastly JS engines are always changing and the more they knows about your code, theoretically the more optimizations it can make. Knowing a variable is const allows for the JIT to make more assumptions. I don't know how much it can optimize today, but given JS is constantly getting recompiled each time you load up your browser or node, new updates could make your existing code run better.
const has some its own benefits as well but using it in those scenarios which you explained, blown my mind, you're actually very right about those code blocks, thumbs up (y)
The talk is a very well told joke. It is weirdly relaxing and entertaining. 😆😆
I’d be pretty annoyed if I’d gone to this conference and the talk turned out to not be serious.
Well said, Jack.
The slide showing you can add to an array is a reason to not use const. what using const in that case does do though is ensures that that const/variable is always an array, which I would say would be a reason to use const.
Exactly. Some protection is better than no protection at all. And if you use TypeScript you can get read-only behavior with no runtime overhead.
Thanks for showing a critique, I appreciate it! The reasons that Ryan stated kind of don't make sense...
At this point, we are in the protestant vs catholic sermons area...
It definitely had a sermon-esque quality to it.
Thanks for putting out this content
Const in JS is different from Const in other languages. In JS, at a minimum const is a signal to other developers and future you that this value isn't SUPPOSED to change and/or that it is a complete throw away once a function has completed. Once you've scanned and parsed a const declaration, you shouldn't have to use mental energy to possibly track any logic that will change that value.
Unfunny 10 minute powerpoint joke, or genuine bikeshedding? Who knows! But i like your breakdown of how to analyze these kinds of talks. That is good info 🍻
In Swift let is const and var is let. Its so messy when working with multiple languages all the time.
In TS I always use const, but only because of such eslint rules that yelled at me. In Swift if you use let (same as const) for an array it would not let you append so there the language is enforcing it. In JS I guess it only stops you from reassigning the variable.
I actually don't have a strong opinion on those things and would switch to let if it makes more sense.
I appreciate the analysis, Jack. The talk didn't convince me, and I've been scratching my head about Twitter the last few days. JavaScript isn't the only language with this behavior, Java's 'final' is nearly the same.
Interesting. I’m hearing other folks say that Java’s final semantics are const all the way down. I’ve been too busy to check into that though.
@@jherr it only affects variable reassignment, which is why they've added some immutable collection types to the JDK.
What I heard was "do what you want, but let me be". I agree with that. Linters yelling at me to not use let, is not my cup of tea. They're variables. It's unsurprising that const doesn't work like Object.freeze, because we have to mutate things too much.
did this talk happen on April 1st ?
Const to me is just a sane, reasonable good practice. I think it is useful to have a "defensive programming" type of mindset as it helps to prevent bugs. So if your default mindset is making sure you want to avoid bugs, and you can make sure a reference to a value can't be mutated (aka by using const) as that can help prevent bugs... then that seems like a good practice to follow.
Damn, great video ! Small video and big punches.
People can say the talk was a joke but Ryan has been years promoting not using const so I think he meant it.
I use almost always const except when I need reassign the variable. This the only reason not to use const for me
In Rust variables are const by default. If you want it mutated, you must declare it mut. If a mutable variable doesn't change, there's a warning. So you see the code and can see perfectly which variables are mutable and not.
Does the compiler check if you mutate your mutable variables and complain if you don't? Just curious.
@@jherr yes: "warning: variable does not need to be mutable"
Interesting. FWIW, the eslint rules for airbnb give that a full error. Thus Ryan's issues with the airbnb lint rules.
@@jherr He he too harsh.
thanks so much for bringing this up, otherwise we as not that experienced devs would be confused by what to use afterwards, you know? this is an example that not every very experienced dev. must have the truth and we should question about it.
Sometimes I have problems with the meaning of const and how it works on JS. But I think is "better" than let when you need to store values and don't need to change the values of the variable. Using const can give clues to compilers, transpilers, optimization plugins, etc. At the end depends on your own criteria how you use the language
I was confused about the let vs const debacle. I always think like this:
I'm declaring a variable for a purpose, will I ever need to change what its pointing to (reassign it)? If yes, then let's use let (maybe I'm doing a sum or an avg without a loop), if not, let's use const (I may just need a way to make sure I'm using the same reference from when I declared it).
If I'm using objects or arrays and I need the content to remain the same always, then I use Object.freeze. But that has nothing to do with let or const
Great take and a good reminder to not follow thought leaders blindly.
Nice video ❤
An argument should be evaluated based on its intrinsic merits and logical structure, rather than relying on external factors like the authority of the person presenting it.
True constness is achieved when a const variable points at an immutable quantity.
If you try to always use const you’ll use map, reduce and filter more correctly too. That’s why trying to use const is good.
I was on the side before that Const was a meaningful tell so should be used for constants, but over time found that `let` was a more meangingful tell "Hey, this changes. If you store a reference to it, it may not match later"
Good advice. This is unfortunately the way many UA-cam channels are working nowadays. They make foolish arguments because it makes people laugh and have their lazy attitudes justified in not learning things which more useful practically than just learning a new shinny framework or language.
I hear the same rants about Uncle Bob's Clean Code. You don't have to agree with everything the book says, (in fact Uncle Bob doesn't ever say that you're doomed if you don't do what he say) but apparently developers having 1 year experience 20 times hate the book and its basic rule of keeping code in unobfuscated form.
were I there I would have walked out. It's like the tab/space debate. Obviously tabs are the only correct choice but I'm not gonna make a talk crying about it.
Tabs forever.
Some of the cooler kids will say let is 3 letters instead of 4.
You can read code much quicker if you know a property isn't changing/reasigned.
Please, for your fellow engineers, use const where possible
It is terrifying to see how industries create trending phrases.
And hearing developers repeat them without testing or even worse without knowing how to prove that a solution is the most optimal. Without any use of any scientific method to prove them.
Jack Thanks for your content.
I've been in the industry since "don't use tables for layout".
He does have a point. I use CAPS for config const that will not change, for example.
Missed a big opportunity at 5:36. Should've applied the screaming case to the // LOL comments too
I love using const with the screaming syntax throughout. In the end, do whatever is consistent within the team you're walking with and don't let random Twitter coder opinions affect what's working. Just my 2 cents!
Еще до того, как TS вошел в повсеместное использование, в моих командах, мы использовали const, что бы уменьшить когнитивную сложность. Ты видишь const и понимаешь, что вот это значение не ожидается, что изменится по ходу работы программы и перестаешь учитывать его возможное изменение при чтении кода (которое обычно происходит чаще написания). Да, это лишь ожидание и мутации возможны. Но у нас хорошее код ревью и использование freeze обычно не поощрялось, как некий оверинжиниринг. И скажу так, за почти 9 лет я не встречался с проблемой с const и ее возможной мутацией. Был лишь 1 момент: при трансляции кода из ES6 в ES5, const менялась на var, что приводило к неожиданным результатам.
Согласованный. Const - это, по крайней мере, хороший способ сообщить о намерении.
Check ASM which compiler will do for code with var, then do it the same for let(const). After that you will see the difference.
Let me give you the reasons for using let over const, which were not mentioned in the talk:
1. const suggests that the object that the variable refers to is immutable. This causes confusion for inexperienced developers / additional cognitive load when reading code.
2. If you use let by default, const communicates the additional semantic meaning "you must not change this!". This is different from "my linter happened to find out that this does not get reassigned"
3. With const everywhere, if at some point you need to modify your code and reassign a variable, you always have to edit two different places in your code, which causes messy diffs
On #1, this doesn't account for primitives, which are truly constant. In addition for objects and arrays it at least keeps the reference constant. And it's a signal to downstream developers that the data is meant to be constant and in most circumnstance is enforced as constant by the runtime.
On #2, sounds good to me.
On #3, in general I try to keep functions short enough that consts are defined very close to where they are used and never reassigned. And if I find myself needing to reassign it it's probably something I need to refactor.
Most of the time I write whole applications that are 100% const. Very rarely do I need to use a const.
@@jherr #1 even for primitives const does not mean that you're dealing with true constant. True constant is something you can replace with it's value everywhere in the code. Something like:
#define PI 3.1415 (in C++). If your value is changed in for loop, or every time you run a function - it is actually not a constant anymore. There is only one reason for REAL constant to change - if you change your source code.
Won't be the first time an author regrets something. Case in point Node and Deno 👀
ALL of us have written code that we look back on with the thought "that could have been better"
That's a daily occurrence for me. :P
@@jherr yup 😅
Existence of OAuth2 too