Can't we just agree to default to const and use let when we want to re-assign a variable. It's so useful and nice and helps readers and helps even you the developer.
This would be like Skala on the variable level but then you make JS a functional programming language but I see where you coming from C# doesn't allow inheritance until a function is virtuell this is kinda similar. My question is more why using so many function pointers which makes debugging hard ?
ES2026 will come with `const const` to indicate that it is truly immutable and we will also get a quadruple equal sign ==== to indicate that the thing is truly truly equal.
Funny! :D But you should have seen the Lisp I was trying to study at the turn of the century. It had equal, identical, equivalent, and I'm sure there were more. I didn't want to know! lol
When I encounter "let" in the code, it stored in some part of my brain. Expecting to find it again later in the code where the value changes. By using "const" for constant value instead of "let". The number of brain energy spent to hold those information are reduced greatly.
This presentation's argument is just so useless, because it is based on the premise, that writing "const" is intenting to mean "the whole structure is immutable", when it means "the name cannot be bound to another value than the initial one". JS isn't by far the only language with semantics like that. So this is rather a skill issue/(intentional) misinterpretation than an argument. Addendum: Mutability of bindings is different than mutability of their contents -Have fun getting your "export let" or "export function" destroyed by assignments on a star-import! (ESMs export bindings not values and "function"+ has the same semantics as "var" bindings!)
It's not even that complex to understand. We assign a lot in js using short hand noadays. Realistically we are just assigning a pointer to a data l structure, then adding items to that structure using its methods. If you just assume it's all just pointers, then this issue just goes away. You don't change a pointer to an object by interacting with that object. They would be impossible to bind and instantiate otherwise.
@@chrisdaman4179 Yes! Finally, som1 else said it too. Its all just pointers and always has been. All the semantic sugar coating and added terminology that doesn't even fit just confuses everyone. Especially those how learn javascript, beginners. Just talk to mathematician about variables and constants, he will look at you in shock on how js uses these words!
@@chrisdaman4179 What proportion of JS devs actually understand pointers properly? As someone who tries to stay as far away from web development as possible, I'm genuinely curious.
The thing is, that Const is really importnat to quickly rtead code. If i have a const, I can make a mental check that it wont mutate and move quicker, it gives me security and more predictability. It also makes code much easier to read. it does not need a functional reason. It just should be a dev info so we can think about other things then that x may mutate.
I can't believe I'm writing this, but does Ryan seriously not understand the difference between constant assignment and immutability? This is the dumbest hill I've ever seen anyone climb. 100% agreed on your convention, this is what I've been doing for years already
I think the c++ equivalency is more like the difference between const string const *, an immutable pointer to an immutable string, and string const *, an immutable pointer to a mutable string, not double indirection
Let say you have some array from the input: const { items } = data; Now you want to output an empty array (or create a new array to populate). With 'const' you can't do items = []; so one would write this: items.length = 0; Did you noticed what just happened? You have mutated an input array. Some other parts of program may rely on it. There is no such problem with let. That's why 'prefer-const' eslint rule is dangerous and should not be used in any professional environment.
@@levsonc But that reasoning relies on the faulty assumption that const means anything other than "you can't re-assign this". If you need to "output an empty array (or create a new array to populate)" you have 2 better solutions than setting length to 0 (which **always** looks like a hack in my eyes): 1) Use a new variable, or 2) change it to let since that's what you actually want to do with it: reassign.
@@trappedcat3615 unless its eating rabbits...then I'm quitting. I don't care that some people eat them. I have some family members that raise and eat rabbit. I respect their choices, but internally I want scream "YOU F*CKING MONSTER!!!!". No, I am not a vegan or vegetarian. I am a carnivore. No, I am not a hypocrite, because that implies that I care about my own consistency in the dietary arena. News flash, I don't.
I use const to protect myself from myself. One of the first warning signs of morbid tech debt is that you need to turn existing consts into lets. It's a wake-up call: "the reason you spent 5 hours debugging one issue is because your codebase is 90% spaghetti, time to face the horror and refactor this crap".
@@Vietnamkid1993 Immutability of the object isn't the point. Immutability of the variable reference is the point. If you are reassigning your variables to new objects all the time in your code, then you are opening the door to all sorts of debugging challenges.
to me the meaning of JS's const is that it's always the same object, not that it's immutable. clear and simple. and quite important for dealing with mutability too: if you mutate it in one place, all other places are guaranteed to observe the change.
In C++ you can absolutely change both the memory that a pointer points to, as well as the address of the pointer. There's a whole can of worms about `const int* someName` vs `int* const someName` vs `const int* const someName` vs `int const* someName` which is pretty annoying to deal with. The older I get, the more I appreciate a really good implementation of const-ness, and in C++ we're closing in on that with constexpr and consteval
I love const as a promise for c/c++. I've caught so many issues where I accidentally tried to change an input of the compiler/lint yells at me before I ruin my entire day refusing to use a debugger instead of prints
One good thing about "const" is that it basically tells you that it's type of "data structure" is constant, so if we do this: const arr = [1,2,3], arr will always be array, even if content changes, if it was "let", you can assigng arr= "123", and it is now a string. Another reason and intention we can provide.
I assumed "const arr = [1, 2, 3]" would make the array immutable. So being able to change it's contents surprised me a bit, but your explanation makes sense.
@mikopiko Const protects the variable, not the things on it. If you want to prevent an object from being modified you should use Object.freeze I always think of it as if I'd written this in C++, if I'm needing to work with an array or object then it'd be a pointer to the object on the heap; protecting the variable would protect the pointer, not the data on the heap. It's the same with JS to an extent, because of how garbage collection works `const arr = [1,2,3];` has `arr` be a reference to a shared memory chunk for the array, and if I assign something else to it `let arr2 = arr` then `arr2` now points to the same chunk of memory(and the reference count increases so it knows when it stops being referenced and can be cleaned up). You can't change `arr` because it's a const, but the data of the array/object has no such protections.
@@mikopiko I wonder: Why though? What makes you think that? What behaviour would you expect if that was the case? Should the runtime throw an Error on "arr[1] = 21"? Should it do that only if the "const arr" declaration is in scope, or even if you pass arr to a function which obviously can't know if it was const- or let-declared? Should it ignore the update like when frozen with Object.freeze? What about a nested array, should the inner arrays also be immutable? What about "let arr1 = [1, 2]; const arr2 = [arr1, 3];", should "arr2[0][1] = 10" error? What about "arr1[1] = 10"? Or just in general, what about "let a = ...; const b = a;", should b be a copy so the object can be immutable, or is a now effectively-const too? There's so many important things that counter the intuition of "const makes the value immutable" to me, that I really am curious how someone comes to it nonetheless. Sorry if that was a lot of questions!
If you make a stupid thing it will be stupid? But that's not an excuse. Why do stupid things? If you're using Typescript - it will throw an error anyway. If not, it's still not that good idea not to use monomorphic structures. Anyway the code should be reviewed and tested. And a good code should be short enough to see such a stupid thing in a moment.
It's kind of fun to be early to a video and land in a fresh comment section, but it's less fun if you decide it's probably not really worth your time and there's no video transcript and summary yet
also Alfred Nobel only changed his mind about 'selling murder' once people accidentally thought he died and posted the crab dance. also LSD has wrecked around 0 lives in total. This guy might be a DARE spokesman, but he sure has no clue about let vs const.
JS devs yet again spending endless time arguing over the correct solution to problems of their own making (and still being more productive than anyone trying anything different because of sheer inertia)
Totally agree with your points. Also I didn't really know the guy in the video, but that typo in the chat gpt stuff really made me lose any trust that I didn't even have yet... I even asked chat gpt how likely it would be, that it would write "thier" instead of "their" and well, it's exceedingly low, since that is not even a real word.
off-topic: as someone who's taken my fair share of LSD, and known people who've taken way way way more than their share...i'm still struggling with Ryan's take away about LSD: "it's pretty undisputed that LSD has wrecked many, many lives" like -- compared to what? and in my experience, which i consider broad, as a travelling musician and ne'er-do-well, i just don't see people abusing LSD like i do other substances. or beliefs. it's not without harm, of course, nothing is. i just don't know anyone who was "wrecked" by it, per my definition of "wrecked". or "by". i support him not drinking coffee and acknowledge nothing is without side effects. i'm just bloody confused here. i'm also a programmer so i am here for a reason! i'm working on an ESP8266 project but in 20 years of off and on dev work this is my first serious foray into C++, and in an embedded environment, i honestly thought the dilemma was twixt #define macros and const. anyway. i look forward to a settled resolution. edit: boy howdy was i unprepared for all of this, dear lord
It's the latent D.A.R.E. brainworms. If he never wanted to try it, and thus never really looked into it, he might just be responding to the childhood propaganda that all drugs are basically supercharged methcocaine that will melt your face off. That program equating things like weed and LSD with meth and crack is probably a major contributor to our current drug crisis, as kids saw their friends smoking pot not getting the horrendous side effects, possibly leading them to trying harder drugs like heroin under the (reasonable) assumption that if they lied about weed, they lied about everything.
Most variables are immutable. I like the way this is expressed in Rust, `let`, `let mut`, and `const`/`static`. By default you write `let`, and upgrade to mutable if needed. In TS, I write `const` by default in 90% of cases, because a variable usually holds a result of something.
Const means you can't rebind the thing. That's really important to know. It doesn't mean the thing is a constant. Once you know that, just use const by default, and use let where necessary, which points out which variables change and which ones don't. This isn't rocket science or something.
I agree. His phasers were set to somewhere between troll and satire for a fun talk. Not sure where, but I'd be surprised if he wasn't less genuinely concerned about it and more wanting to sit back, put his hands behind his head, and watch the ruffled feathers fly with a big smirk on his face. ( I don't know Ryan Florence, and he could have a sarcastic streak that I just don't know about).
What I think many people are missing in the imperative world is that FP programmers don't need to freeze objects or protect themselves from mutations. We simply don't do it. If we do it, it's in a tiny and controlled scope. The mental load is just so much lower when you do that. When a FP programmer looks for an immutable data structure, it is not to prevent mutations. They don't do mutations, it is to have an efficient data structure, with structural sharing for example
Oh man, the beginning and the complete misunderstanding of everything there from LSD (Albert Hoffmann, what he was doing etc..) all the way to the actual topic discussed makes me gag...
Up to a point. Eventually the developers need to look at how people actually use what they have built and reassess whether their intentions reflect what is actually wanted.
I feel that I learned a lot from this video. Essentially, you should use const by default and only use let if you intend to change it. I was very confused about when to use const, but now I understand it. Thanks for the video.
Well, he also proudly claimed to be jerk (but doesn’t swear) and the faked a chat gpt response without taking the care to spell check it. People like this are so dangerous. He has all the hallmarks of a “bad person” while clearly believing himself to in fact be the opposite. So sketchy 🚩⚠️⛔️
No. In C++ you have int * (pointers to integers), int const * (pointer to const integers), int * const (const pointers to integers), int const * const (const pointers to constant integers). All of them are pointers, yet quite different.
i wouldn't call this clickbait. Theo is just putting out a statement ("const is a mistake") that he saw somewhere and is surprised by it, and wants to challenge it. Nowhere does Theo say that the statement in his title or thumbnail is his own opinion.
I have literally never seen an argument about whether to use const vs let. If anybody has a meeting to waste your time about that, their real purpose was to fill time, and they'd have still created a nonsense meeting about something else pointless.
i agree with you theo. i only use 'let' for simple types (string, number, boolean) when i NEED to change the variable, like to build up a string or something. const for everything else.
I've had my choice of const over let prevent a few bugs, so I'm pretty happy with treating it as a constant reference to an object. The use case is exactly as explained: sometimes, you accidentally reassign something, or end up reassigning the wrong binding (since JS allows name clashes as long as they're in different scopes). There's use cases for global objects that shouldn't be reassigned, but where mutation is desirable, like a global table where you register handlers. You don't want someone to be clever and try to replace that object entirely, and the use of private variables (the # syntax ones) prevents actually reaching the storage object so all that's left is the interface to it. That works fine. I think using const also has some implications with the JIT because it can skip looking up the name and dereferencing the pointer every time you use it. It knows it'll always point to the same object so it doesn't have to account for it potentially changing. Apparently that can lead to some nice optimizations with deep nested closures, although I guess a more advanced optimizer could determine it does not get rebound. But that's the reason I learned as to why do it that way, whenever you can use language features to make it easier for the optimizer, the better the chances the optimizer will do its job well. I wouldn't hate a way to also make things immutable, but it's pretty well understood that const in JS is to protect the binding. Even in C++ you have slap a bunch of const everywhere to really make it not-so-mutable (const T* thing() const) because the first const applies to the return type, not that the function can't mutate the object.
I get what are you saying, but I really like Dart implementation For different variable purpouse they have different modifier: 1. const -> real Constant (It forces you to have const threw the whole tree) 2. final -> js const - not changable, but inside modifiable 3. var -> js let (it does not have js var) But as it is said in DreamBread to be able to change it, but to have like array constant you woud do it like: var arr = const ['A', 'B', 'C'];
in C++, we can do: std::vector vec = {1,2,3,4,5}; std::vector* const constantPointerToAVariable = &vec; constantPointerToAVariable->push_back(6); // ok const std::vector* const constPointerToAConstVar = &vec; constPointerToAConstVar->push_back(7); // error there are other things but i'm just gonna talk about this one, javascript constants are a constant to a pointer, which means the variable itself can change, the pointer cannot. however, for the second case it's a constant pointer to a constant, which means neither the pointer can change nor the values
12:20 I always use the function keyword to declare a function, and not a function expression. I use arrow functions only when it's not required to name the function. So JS devs might just agree with me ig.
11:00 It's still a variable (resp. constant), which happens to have a function type. However, I mostly agree with you on the topic. Also, it's amusing to me that there is a whole talk about invalidating one concept (const) with another (immutability) when both are orthogonal. Of the talk, the introduction slides were the most interesting ones.
const and let were created to fix the var hoisting. const just means that the reference cannot be changed - it does not try to prevent change to the thing being referred. C# does the same thing ... come on But, in reality, const is just a hint that the thing probably should not change. love this: "const is *; let is **" +1 for the notion that using const as the default qualifier allows let to be more meaningful! var is the crazy thing ...
Here's my take as a total beginner who is struggling to learn javascript at a senior age. Never knew when or where to use const vs. let. I don't know anything about mutation or that stuff. But what summarizes the whole video for me was your remark "const* and let**". I don't know anything about C++ and memory pointers either. But I find it easier to learn and "think" programming when concepts are explained in a very basic and primitive way. Everything starts to build up from there. Regardless that's it would be easier for me to use "let" almost everywhere, from now on I really understand the difference between both and I can think of both in a very solid way. Of course, as I mentioned before, this is the view of a newbie. Thanks for this video!
What he says about * and ** in C/C++ is incorrect. * is a pointer to a memory address and ** is a pointer to a pointer. Both can be changed to point at different objects. So, int *x = &y; which may be the first element in an array can be changed to *x = &z; which can be the first element in a completely different array. If you want to prevent the pointer from being re-assigned you have to add a const before the declaration. So, const int *x = &y; prevents the change. When I was programming in C the const keyword didn't exist for C. I believe C++ had it and I maybe wrong, but I believe C has it now.
@@augustinechulu5226 speaking with conviction about something you have no firsthand knowledge and could easily have first hand knowledge of is the literal definition of bullshit. Just say “I don’t know, but I read….”
When I reconcile Ryan's arguments, David Herman's tweets, and Theo's argument in my brain, the base problem across all of those that maybe 'const' was a poor choice of key word that wasn't specific enough (some argue it should mean "cannot change value", and others are fine with "cannot be reassigned"). Was there a better key word that could have chosen to add to es6 if David's intention (don't change the value) was different than the actual implementation (don't reassign)? I assume this is the crux of David's regret.
No, the crux of the regret is that it became a debate to begin with. And it only became a debate because there's not much value in making a distinction between variables that are reassigned or not. I can say that I've worked in codebases that used let for everything and other codebases that tried to use const wherever possible, and the difference was meh. Use const if you want, it doesn't matter; just don't think it will actually do anything.
after learning the hard way, we got a rule on work, we can't use var or let and only const, why well, when you don't reassign variables you get code you read from top to bottom, without crazy things in loop where the code do one thing and then if something next time if some thing else then it do that. this is hard to understand and read, making that kind of code full of bugs, so now with only const no one make that kind of crazy code, and we half the amount of bugs, and we make more features and look less in the black hole of despair. in the start people think you can't do stuff without let, but you are wrong, you are just thinking of the wrong way to fix that problem, there is always a simple way with reduce or filter to make the loops only do one pass, you can then reduce the result again and again, so each pass will fix one of the problems you used let for.
Damn, your explanation with a pointer and double-pointer at 15:24 was spot on, it finally clicked with me. Before this, this whole discussion seemed like a purely cultural/philosophical debate about religion and metaphysics. It still does to me, but now I feel like I actually know what the underlying thing is
As a former C++ developer, that comparison is not great. Of course using double pointers is different than using sinlge pointers, it's more convoluted. Using variables declared with let and const is pretty simar.
The thing is that the argument "const is not for immutability but to prevent reassignment" only exists as a ex-post justification for the bad implementation of const in JS. In C++, const is properly implemented and absolutely nobody argues it should be only for reassignment. It actually prevents mutation (and a lot of bugs that come with it).
C++ for all its warts got many things right. Const should be default but otherwise it got const right. References and values being non-nullable by default was also right. You want null, then use a pointer. But it is opt-in. But then came Java and everyone forgot about the good things C++ had.
I'm primarily a Java dev and JS const has the same semantics as Java's final keyword. The "final" behavior should be default behavior of variables, because changing the object reference of a variable opens the door to endless possible bugs. Javascript is even more so prone to these bugs due to the global scope in browsers. I think the JS designers choosing the keyword "const", implying a constant, is the root of the confusion. But the behavior is fine and should be preferred over "let"
Scope (Public, Protected, Privated) is generally recommended to be as restricted as possible; The same rationale applies to let vs const, while not actually immutable it is still more restrictive than let; These restrictions on const result in usually only having to look for areas of modification rather than complete reassignment
it's a multiparadigm language and the keyword is CONST not IMUT, it was never supposed to behave like IMUT, I don't know where these guys get the idea that const has to be imutable. Const means that the reference is constant. I agree with you here, LET and CONST have more communication value to us if we use const to indicate that a value is not being reassigned.
JS wasn't a mistake, the mistake was people trying to take it out of it's rapid prototyping scripting box and turning it into Typescript, Node, full blown complex frameworks, basically going backwards from dumb quick language into what made it in the first place.
That's something I really like in Rust. You can redefine variables/constants (shadowing) and it's encouraged. And also constants are true constants, not constant references to something that might be mutable.
It's kinda ironic in Javascript that we use CONST but then change it's value anyway as that's the const only care for the declaration, not what's within it.
Makes sense to me actually. Just like you have shallow copies of arrays for a reason you have shallow const. If you want a deep copy you can just freeze it.
@@PS-dp8yg when you have another reference to the underlying data . This is also the problem if they one day change it from half-backed to the normal implementation of const so many things will break.
No, you cannot change the value. You might be confused by the semantic. const x = {a:1}; corresponds to struct{int a} *const x =…; in C/C++ and some other similar languages, as opposed to struct{int a} const *const x =…; The “reference” (“pointer”) is indeed constant and cannot be modified, but the fields of the structure that we are pointing to are not necessarily constant. To make them constant you would have to define the field “a” in {a:1} as a “read-only” property. Otherwise, you are defining it with the regular defaults (enumerable, writeable, configurable, etc.) You can test the following code in JS to verify that “const” prevents you from modifying the object. const x = {a:1}; x = {b:2}; You will get an error.
When i did Swift programming, i always used const except when i needed to reassign a variable and didn't want to toss the code into a separate function.
100% on board with your conventions. I have arrived at the same myself. Having a reference to an object that lets you mutate it only under its own rules should not be controversial. Const is a great signal to the developer to make them ask the questions: - Is my re-assignment method inefficient? - Is there a correct place in a lifecycle that this should be updated?
@@hansmeyer2@hansmeyer2 The short answer is that the return value / type is 'never' defined as opposed to being explicitly returning nothing such as with `if (condition) return;` or ending the method explicitly with an empty return. The value will be undefined whether 'never' or 'void', it's just a semantic difference and is more-or-less interchangeable. The distinction may be due to how deterministic the code is assumed to be - we know with pretty much 100% certainty the behavior a function invoking console.log() is, but there is a possibility that the first method could never finish or throw an error (hence actually never hitting end of function, therefore never even implicitly returning). Promise.reject() returns Promise, whereas Promise.resolve() will return Promise
@@stevenbasher5363 Implicit return yields void though, and nothing is being awaited in the original function, so why not Promise? EDIT: nvm, it's the "use server". missed that earlier in the video.
Yes, I agree totall. The difference between constant references, etc. has meaning. The guy never comes up with an example which shows where const would be confusing and potentially lead to programming the wrong thing! Syntactically I would prefer js doing something like: `let immutable myVariable = ...` (or some shorter keyword than 'immutable') as a modifier for let. Immutable function parameters would also be nice to have.
I seem to have totally right to rely on your wisdom.. if i would have discovered the posts from es6 creator, i would have been hyped. Thank you for your professional yet simple moderate addressing..
Well, I use `const` kinda as an annotation, where I create a variable that's not meant to be replaced, e.g. the HTML element the function we're in works on. So I store the element in a `const`, to modify its attributes but not replace it as a whole as I then would stop doing stuff to the element the user sees.
I would also like to mention that TypeScript allows the declaration of actually constant arrays which can then also be used in type definitions: const vars = ["a" ,"b", "c"] as const;
The way Kotlin handles the immutability issue is by in addition to having var (==let) and val (==const), making collections immutable _by_ _default_ . You have to go out of your way to get a mutable Array etc. That would have been a change too far for JS, but at least it's moving in the right direction by completing the set of non-mutating array operations (toSorted(), toSpliced()).
Ryan's talk was clearly intended to be humorous, especially invoking ChatGPT as an authority (given that the output was clearly edited). Not distinguishing between integrals and ref's makes it an in joke for people sufficiently knowledgable about the language. Using screaming case is a hold over from when editors lacked tooltip context to understand whether, in a language like C, the symbol was a macro or a variable. Screaming case is rarely useful beyond TOUCH_THIS_AND_DIE or UNTIL_HELL_FREEZES_OVER semantics.
Exactly, Theo, exactly! Beautifully put, it's not that "const" has a specific meaning, it's that "let" is supposed to mean something specific, i.e. reassignment. Maybe that wasn't the original creator's intention (I don't know), but it certainly makes sense. Let's just agree that Rust provided the best solution: "let": immutable by default, "let mut": explicitly mutable, no misunderstanding possible. But "const" by default is a more than reasonable fallback.
Strong agree on basically all of this. I am very much in favor of using `const` by default and using `let` to signal that reassignment is possible. And I'll use screaming case to define what you call "true constants" here. But, also, Records and Tuples are currently late-ish stage proposals and will hopefully soon be able to soon make creating true constants much more ergonomic. Kinda wish `const` did that by default, but... We don't live in that world. Taking a hint from Rust here, I'd be even more happy with a way of declaring things as mutable or not from the beginning, but... It's easy enough to just know a pretty fundamental thing about JS and know `const` is about assignment rather than mutability.
18:00 About doing those ChatGPT and other AI "gotcha" posts... The conversations are typically salted by first prompting the the AI model to be certain way or bias it towards a viewpoint. The actual post that is shown is done after that and is like the second or third post in the conversation.
15:25 I couldn't agree more. Even more, when you go to ANY language, even constants are mutable when you assign them mutable object/instance/structure. The original intended use seems to have been limited to immutable value which was most likely a string. Nice demo though with Object.freeze which nobody uses. Not that nobody should...
In Typescript there is a kind of "const const" when declaring an immutable array or object with the "as const". I always use it when declaring "actual constants". Typescript seems pretty aware of the problem raised with let and mutable const because when u declare a "const myArray = ['abc', 'def']" it says it's an array of strings and can be mutated. If you declare with "const myArray = ['abc', 'def'] as const", it says it's an array containing 'abc' and 'def' and you can't mutate it.
100% agree. I come from C++ and moved to frontend development and I will always default to const if I have no INTENTION to change what it points to. I use let rarely and that becomes even more rare the more we move towards fluent array transformations.
I recall being led to believe there was a performance win by using const due saving on GC checking or some such thing. Micro-optimization for most projects, but those sorts of things are good habits to form. I could easily be mistaken, but that's why I formed the habit.
I totally agree with this. Const should be the default, and let should only be used when reassignment is needed. Although, I do partly wish that const meant completely immutable (or have some third option)
Can't we just agree to default to const and use let when we want to re-assign a variable. It's so useful and nice and helps readers and helps even you the developer.
yeah why this channels have to over complicate everything just to make a video about it???
That's it
This would be like Skala on the variable level but then you make JS a functional programming language but I see where you coming from C# doesn't allow inheritance until a function is virtuell this is kinda similar. My question is more why using so many function pointers which makes debugging hard ?
hasn't it always been like this since const was introduced? i don't know any person working with it another way lol
@@Fiercesoulking Dude what the fuck. xD
Ah, the good old let-leaning vs constervative
😂
WILDLY underrated comment! 😂
W comment
Varistocrats relegated to history
Vary clevar
ES2026 will come with `const const` to indicate that it is truly immutable and we will also get a quadruple equal sign ==== to indicate that the thing is truly truly equal.
I think we need bakers dozen of equal signs just to make sure.
More like Records and Tuples.
This syntax is coming.
Does anyone not know about this?
Great idea!
==== states that two variables are ===, but not ==.
Some believe const const const is also on the way
Funny! :D But you should have seen the Lisp I was trying to study at the turn of the century. It had equal, identical, equivalent, and I'm sure there were more. I didn't want to know! lol
When I encounter "let" in the code, it stored in some part of my brain. Expecting to find it again later in the code where the value changes.
By using "const" for constant value instead of "let". The number of brain energy spent to hold those information are reduced greatly.
Exactly. It's not about runtime really, it's about making the code much more readable.
This presentation's argument is just so useless, because it is based on the premise, that writing "const" is intenting to mean "the whole structure is immutable", when it means "the name cannot be bound to another value than the initial one". JS isn't by far the only language with semantics like that. So this is rather a skill issue/(intentional) misinterpretation than an argument.
Addendum: Mutability of bindings is different than mutability of their contents -Have fun getting your "export let" or "export function" destroyed by assignments on a star-import! (ESMs export bindings not values and "function"+ has the same semantics as "var" bindings!)
It's not even that complex to understand. We assign a lot in js using short hand noadays. Realistically we are just assigning a pointer to a data l structure, then adding items to that structure using its methods.
If you just assume it's all just pointers, then this issue just goes away. You don't change a pointer to an object by interacting with that object. They would be impossible to bind and instantiate otherwise.
@@chrisdaman4179 Yes! Finally, som1 else said it too. Its all just pointers and always has been.
All the semantic sugar coating and added terminology that doesn't even fit just confuses everyone. Especially those how learn javascript, beginners.
Just talk to mathematician about variables and constants, he will look at you in shock on how js uses these words!
@@chrisdaman4179 What proportion of JS devs actually understand pointers properly? As someone who tries to stay as far away from web development as possible, I'm genuinely curious.
@@Bobbias I would hope that the people giving talks would be aware at least...
The thing is, that Const is really importnat to quickly rtead code. If i have a const, I can make a mental check that it wont mutate and move quicker, it gives me security and more predictability. It also makes code much easier to read. it does not need a functional reason. It just should be a dev info so we can think about other things then that x may mutate.
I can't believe I'm writing this, but does Ryan seriously not understand the difference between constant assignment and immutability? This is the dumbest hill I've ever seen anyone climb.
100% agreed on your convention, this is what I've been doing for years already
I think the c++ equivalency is more like the difference between const string const *, an immutable pointer to an immutable string, and string const *, an immutable pointer to a mutable string, not double indirection
Let say you have some array from the input:
const { items } = data;
Now you want to output an empty array (or create a new array to populate). With 'const' you can't do
items = [];
so one would write this:
items.length = 0;
Did you noticed what just happened? You have mutated an input array. Some other parts of program may rely on it.
There is no such problem with let. That's why 'prefer-const' eslint rule is dangerous and should not be used in any professional environment.
@@FadkinsDietwhen I saw the C++ tweet I was very confused
@@levsonc But that reasoning relies on the faulty assumption that const means anything other than "you can't re-assign this". If you need to "output an empty array (or create a new array to populate)" you have 2 better solutions than setting length to 0 (which **always** looks like a hack in my eyes): 1) Use a new variable, or 2) change it to let since that's what you actually want to do with it: reassign.
@@levsonc I'm sorry, why would you ever write `items.length = 0`, and how is the behaviour any different between const and let here?
If you’re in a company that runs a meeting about const vs let quit immediately
Not if the pay is good. They can have meetings about rabbits for all I care.
@@trappedcat3615 Companies that do this, never pay good for long.
@@trappedcat3615 unless its eating rabbits...then I'm quitting. I don't care that some people eat them. I have some family members that raise and eat rabbit. I respect their choices, but internally I want scream "YOU F*CKING MONSTER!!!!".
No, I am not a vegan or vegetarian. I am a carnivore. No, I am not a hypocrite, because that implies that I care about my own consistency in the dietary arena. News flash, I don't.
@@akam9919 bro calm down it just tastes good
I had this meeting in a company I worked in. Was super annoying too.
const is not to protect us from mutation, it is to protect us from javaScript
It doesn't though. Need TypeScript "as const" for that.
I use const to protect myself from myself.
One of the first warning signs of morbid tech debt is that you need to turn existing consts into lets. It's a wake-up call: "the reason you spent 5 hours debugging one issue is because your codebase is 90% spaghetti, time to face the horror and refactor this crap".
const on an array or object still allows values to be reassigned in it. We need freeze too
@@Vietnamkid1993or typescript as const
@@Vietnamkid1993 Immutability of the object isn't the point. Immutability of the variable reference is the point. If you are reassigning your variables to new objects all the time in your code, then you are opening the door to all sorts of debugging challenges.
to me the meaning of JS's const is that it's always the same object, not that it's immutable. clear and simple. and quite important for dealing with mutability too: if you mutate it in one place, all other places are guaranteed to observe the change.
"Defaulting to `const` actually makes 'let` mean something" (paraphrasing of course)
and makes const means nothing, specially TS "as const", you've exchange half a dozen eggs for 6 eggs.
@@icavalheiro "as const" in TS actually has a lot of useful applications in typing.
Superior title detected
At this point choosing JavaScript as my main programming language is the only mistake I made.
Any kind of scripting language should not be the mian language but System language. Trust me I know it by hard way
😂😂 JavaScript is the only alternative
But isJSYourMainLanguage const or let?
YOU are the one that choose it, or you use it because it's the thing that builds the web ? 😂
@@Leonhart_93 Well actually the web is built on top of java and php
In C++ you can absolutely change both the memory that a pointer points to, as well as the address of the pointer.
There's a whole can of worms about `const int* someName` vs `int* const someName` vs `const int* const someName` vs `int const* someName` which is pretty annoying to deal with.
The older I get, the more I appreciate a really good implementation of const-ness, and in C++ we're closing in on that with constexpr and consteval
I think the way Rust does it is really nice. Let is for immutable and non-reassignable values and let mut is for both mutable and reassignable values.
I love const as a promise for c/c++. I've caught so many issues where I accidentally tried to change an input of the compiler/lint yells at me before I ruin my entire day refusing to use a debugger instead of prints
the phrase "const correctness" still gives me mild ptsd from my c/c++ years.
that why you use pointers only in containers.
Wait, What's the difference between 'const int * myPtr' and 'int const * myPtr'? I thought those are equivalent?
One good thing about "const" is that it basically tells you that it's type of "data structure" is constant, so if we do this: const arr = [1,2,3], arr will always be array, even if content changes, if it was "let", you can assigng arr= "123", and it is now a string. Another reason and intention we can provide.
I assumed "const arr = [1, 2, 3]" would make the array immutable. So being able to change it's contents surprised me a bit, but your explanation makes sense.
@mikopiko
Const protects the variable, not the things on it.
If you want to prevent an object from being modified you should use Object.freeze
I always think of it as if I'd written this in C++, if I'm needing to work with an array or object then it'd be a pointer to the object on the heap; protecting the variable would protect the pointer, not the data on the heap.
It's the same with JS to an extent, because of how garbage collection works `const arr = [1,2,3];` has `arr` be a reference to a shared memory chunk for the array, and if I assign something else to it `let arr2 = arr` then `arr2` now points to the same chunk of memory(and the reference count increases so it knows when it stops being referenced and can be cleaned up).
You can't change `arr` because it's a const, but the data of the array/object has no such protections.
@@mikopiko I wonder: Why though? What makes you think that? What behaviour would you expect if that was the case? Should the runtime throw an Error on "arr[1] = 21"? Should it do that only if the "const arr" declaration is in scope, or even if you pass arr to a function which obviously can't know if it was const- or let-declared? Should it ignore the update like when frozen with Object.freeze? What about a nested array, should the inner arrays also be immutable? What about "let arr1 = [1, 2]; const arr2 = [arr1, 3];", should "arr2[0][1] = 10" error? What about "arr1[1] = 10"? Or just in general, what about "let a = ...; const b = a;", should b be a copy so the object can be immutable, or is a now effectively-const too?
There's so many important things that counter the intuition of "const makes the value immutable" to me, that I really am curious how someone comes to it nonetheless. Sorry if that was a lot of questions!
If you make a stupid thing it will be stupid? But that's not an excuse. Why do stupid things? If you're using Typescript - it will throw an error anyway. If not, it's still not that good idea not to use monomorphic structures. Anyway the code should be reviewed and tested. And a good code should be short enough to see such a stupid thing in a moment.
I would argue that with let, you should not be able to change data types a variable points to. And const should be for immutable objects.
i will unsubscribe if this is a serious thing
😂😂😂
Pff why do I have to go through an intro about drugs to find out :-/
It's kind of fun to be early to a video and land in a fresh comment section, but it's less fun if you decide it's probably not really worth your time and there's no video transcript and summary yet
@@somebody-anonymouswhat?
Because const is kind of a lie. Const is an immutable reference to a value, not a reference to an immutable value.
2:35 this is not true, albert hofmann worked for a pharma company that was researching something against bleeding in pregnancies. Not adhd related.
It just speaks wonders of the credibility of the presenter that makes disingenuous let vs const arguments
@@thomassynths and goes on wild tangents
also Alfred Nobel only changed his mind about 'selling murder' once people accidentally thought he died and posted the crab dance.
also LSD has wrecked around 0 lives in total. This guy might be a DARE spokesman, but he sure has no clue about let vs const.
Ah yes, JS devs discussing stupid shit with ridiculous arguments and fallacies
"let is prettier and easier to pronounce than const", JS devs in a nutshell
JS devs yet again spending endless time arguing over the correct solution to problems of their own making (and still being more productive than anyone trying anything different because of sheer inertia)
Would you rather join the C++ dev discussion East Const vs West Const?
@@baummensch49 I'll stick to my c90
It's not "js devs", it's "stupid people".
Totally agree with your points. Also I didn't really know the guy in the video, but that typo in the chat gpt stuff really made me lose any trust that I didn't even have yet...
I even asked chat gpt how likely it would be, that it would write "thier" instead of "their" and well, it's exceedingly low, since that is not even a real word.
yea, the translation from tokens to words seems impossible for something like "thier"
off-topic:
as someone who's taken my fair share of LSD, and known people who've taken way way way more than their share...i'm still struggling with Ryan's take away about LSD: "it's pretty undisputed that LSD has wrecked many, many lives"
like -- compared to what? and in my experience, which i consider broad, as a travelling musician and ne'er-do-well, i just don't see people abusing LSD like i do other substances. or beliefs. it's not without harm, of course, nothing is. i just don't know anyone who was "wrecked" by it, per my definition of "wrecked". or "by". i support him not drinking coffee and acknowledge nothing is without side effects. i'm just bloody confused here.
i'm also a programmer so i am here for a reason! i'm working on an ESP8266 project but in 20 years of off and on dev work this is my first serious foray into C++, and in an embedded environment, i honestly thought the dilemma was twixt #define macros and const. anyway.
i look forward to a settled resolution.
edit: boy howdy was i unprepared for all of this, dear lord
It's the latent D.A.R.E. brainworms. If he never wanted to try it, and thus never really looked into it, he might just be responding to the childhood propaganda that all drugs are basically supercharged methcocaine that will melt your face off.
That program equating things like weed and LSD with meth and crack is probably a major contributor to our current drug crisis, as kids saw their friends smoking pot not getting the horrendous side effects, possibly leading them to trying harder drugs like heroin under the (reasonable) assumption that if they lied about weed, they lied about everything.
Most variables are immutable. I like the way this is expressed in Rust, `let`, `let mut`, and `const`/`static`. By default you write `let`, and upgrade to mutable if needed. In TS, I write `const` by default in 90% of cases, because a variable usually holds a result of something.
Const means you can't rebind the thing. That's really important to know. It doesn't mean the thing is a constant. Once you know that, just use const by default, and use let where necessary, which points out which variables change and which ones don't. This isn't rocket science or something.
you could swear these guys are just dorks with the rocket scientists levels of self-importance.
The conference talk feels like a troll
I agree. His phasers were set to somewhere between troll and satire for a fun talk. Not sure where, but I'd be surprised if he wasn't less genuinely concerned about it and more wanting to sit back, put his hands behind his head, and watch the ruffled feathers fly with a big smirk on his face. ( I don't know Ryan Florence, and he could have a sarcastic streak that I just don't know about).
And not even a good one. I remember when people put effort into trolling. It truly is a art.
Aren't they all?
@@Asdayasman no need to be smart when theres wise asses like theo around who eat it all up
What I think many people are missing in the imperative world is that FP programmers don't need to freeze objects or protect themselves from mutations. We simply don't do it. If we do it, it's in a tiny and controlled scope. The mental load is just so much lower when you do that. When a FP programmer looks for an immutable data structure, it is not to prevent mutations. They don't do mutations, it is to have an efficient data structure, with structural sharing for example
Oh man, the beginning and the complete misunderstanding of everything there from LSD (Albert Hoffmann, what he was doing etc..) all the way to the actual topic discussed makes me gag...
2:22 Theo just casually calling an audience member a chatter lol
Intent is always super important for fellow developers that come along after you. This cannot be overstated.
Up to a point. Eventually the developers need to look at how people actually use what they have built and reassess whether their intentions reflect what is actually wanted.
I feel that I learned a lot from this video. Essentially, you should use const by default and only use let if you intend to change it. I was very confused about when to use const, but now I understand it. Thanks for the video.
This is the kind of argument you come up with when you're invited to speak at a conference and have nothing to talk about.
"lsd has ruined countless lives"?? What does he think lsd is? I'm almost sure he just totally made that up, that's just a completely unfounded claim
Well, he also proudly claimed to be jerk (but doesn’t swear) and the faked a chat gpt response without taking the care to spell check it. People like this are so dangerous. He has all the hallmarks of a “bad person” while clearly believing himself to in fact be the opposite. So sketchy 🚩⚠️⛔️
I guess the only reasonable reaction is for to me to change all my code to use var 😂
@@alilseman2979yeah, pretty large air of superiority around that guy. I get it’s a bit of a standup performance, but it kind of reeks of narcissism…
Just imagine const objects, arrays and functions are pointers.
It all makes sense if you think it that way.
No. In C++ you have int * (pointers to integers), int const * (pointer to const integers), int * const (const pointers to integers), int const * const (const pointers to constant integers). All of them are pointers, yet quite different.
@@sokacsavok so const in JS is just a const ref to a mutable object. That makes sense right?
@@sokacsavok JavaScript doesn't have all types of pointers
The more times I'm watching the Let Me Be talk, the more I think it's more like a satire.
Yeah it totally feels that way. It's hard for me to think it's serious
I just clicked this video only to pause it at 0:00 and write the comment that I'm 99,9% sure it's just another theo'ish clickbait title
Sorta, but it was someone else that said it
Folks who complain about clickbait so much need to spend another decade getting used to the internet. Its normal and everyone does it.
i wouldn't call this clickbait. Theo is just putting out a statement ("const is a mistake") that he saw somewhere and is surprised by it, and wants to challenge it. Nowhere does Theo say that the statement in his title or thumbnail is his own opinion.
@@trappedcat3615 being "normal" does not make it good.
"LSD has wrecked many lives"
(X) Doubt
fr
I have literally never seen an argument about whether to use const vs let. If anybody has a meeting to waste your time about that, their real purpose was to fill time, and they'd have still created a nonsense meeting about something else pointless.
I’ve been programming in JavaScript the past 7 years. Had no idea let vs const was this controversial.
I'm disappointed that clickbait made me spend 30 minutes on this video.
At least the ending is really good :)
welcome to this channel
@@lbgstzockt8493 And bad mustaches
i agree with you theo. i only use 'let' for simple types (string, number, boolean) when i NEED to change the variable, like to build up a string or something. const for everything else.
LSD ruined lives? lol
I've had my choice of const over let prevent a few bugs, so I'm pretty happy with treating it as a constant reference to an object. The use case is exactly as explained: sometimes, you accidentally reassign something, or end up reassigning the wrong binding (since JS allows name clashes as long as they're in different scopes).
There's use cases for global objects that shouldn't be reassigned, but where mutation is desirable, like a global table where you register handlers. You don't want someone to be clever and try to replace that object entirely, and the use of private variables (the # syntax ones) prevents actually reaching the storage object so all that's left is the interface to it. That works fine.
I think using const also has some implications with the JIT because it can skip looking up the name and dereferencing the pointer every time you use it. It knows it'll always point to the same object so it doesn't have to account for it potentially changing. Apparently that can lead to some nice optimizations with deep nested closures, although I guess a more advanced optimizer could determine it does not get rebound. But that's the reason I learned as to why do it that way, whenever you can use language features to make it easier for the optimizer, the better the chances the optimizer will do its job well.
I wouldn't hate a way to also make things immutable, but it's pretty well understood that const in JS is to protect the binding. Even in C++ you have slap a bunch of const everywhere to really make it not-so-mutable (const T* thing() const) because the first const applies to the return type, not that the function can't mutate the object.
I get what are you saying, but I really like Dart implementation
For different variable purpouse they have different modifier:
1. const -> real Constant (It forces you to have const threw the whole tree)
2. final -> js const - not changable, but inside modifiable
3. var -> js let (it does not have js var)
But as it is said in DreamBread to be able to change it, but to have like array constant you woud do it like:
var arr = const ['A', 'B', 'C'];
in C++, we can do:
std::vector vec = {1,2,3,4,5};
std::vector* const constantPointerToAVariable = &vec;
constantPointerToAVariable->push_back(6); // ok
const std::vector* const constPointerToAConstVar = &vec;
constPointerToAConstVar->push_back(7); // error
there are other things but i'm just gonna talk about this one, javascript constants are a constant to a pointer, which means the variable itself can change, the pointer cannot. however, for the second case it's a constant pointer to a constant, which means neither the pointer can change nor the values
12:20 I always use the function keyword to declare a function, and not a function expression. I use arrow functions only when it's not required to name the function. So JS devs might just agree with me ig.
Functions can be reassigned just like with let, so that's also a bit annoying. With modules it's less of an issue though.
I just learned something, and changed my mind about this. Great video, thank you.
The guy's shitting on LSD ruined any of his credibility
He said he never swears and then later does 😏
11:00 It's still a variable (resp. constant), which happens to have a function type. However, I mostly agree with you on the topic.
Also, it's amusing to me that there is a whole talk about invalidating one concept (const) with another (immutability) when both are orthogonal.
Of the talk, the introduction slides were the most interesting ones.
In C++ you don't need to go to ** to do the analogy
int a = 5;
const int a = 5;
int* a = new int(5);
you should never use new outside of a container anyway.
I think Theo's talking about "const pointer to object" and "const pointer to pointer to object". otherwise it doesn't make sense.
const and let were created to fix the var hoisting.
const just means that the reference cannot be changed - it does not try to prevent change to the thing being referred.
C# does the same thing ... come on
But, in reality, const is just a hint that the thing probably should not change.
love this: "const is *; let is **"
+1 for the notion that using const as the default qualifier allows let to be more meaningful!
var is the crazy thing ...
What lives has LSD wrecked? Perfect example of someone talking about something they know nothing about
Well, it doesn't get much better after that comment :P
Whenever I see a video on this channel I usually expect the information to be bad or pointless. Glad to see it still doesn't disappoint.
I haven't watched the video yet but im going to assume you're wrong
Nope, just a little clickbait :D
Here's my take as a total beginner who is struggling to learn javascript at a senior age. Never knew when or where to use const vs. let. I don't know anything about mutation or that stuff. But what summarizes the whole video for me was your remark "const* and let**".
I don't know anything about C++ and memory pointers either. But I find it easier to learn and "think" programming when concepts are explained in a very basic and primitive way. Everything starts to build up from there. Regardless that's it would be easier for me to use "let" almost everywhere, from now on I really understand the difference between both and I can think of both in a very solid way. Of course, as I mentioned before, this is the view of a newbie. Thanks for this video!
What he says about * and ** in C/C++ is incorrect. * is a pointer to a memory address and ** is a pointer to a pointer. Both can be changed to point at different objects. So, int *x = &y; which may be the first element in an array can be changed to *x = &z; which can be the first element in a completely different array. If you want to prevent the pointer from being re-assigned you have to add a const before the declaration. So, const int *x = &y; prevents the change. When I was programming in C the const keyword didn't exist for C. I believe C++ had it and I maybe wrong, but I believe C has it now.
Man who has never tried LSD has many opinions on LSD. not a strong start for my dude.
By your logic no one should talk about anything they haven't had direct experience with and you're just wrong
@@augustinechulu5226 speaking with conviction about something you have no firsthand knowledge and could easily have first hand knowledge of is the literal definition of bullshit. Just say “I don’t know, but I read….”
No but their opinion is definitely less valid than someone who has. Just how it goes shrug.
the last sentence was so good, one of your greatest videos theo
good shit brother
When I reconcile Ryan's arguments, David Herman's tweets, and Theo's argument in my brain, the base problem across all of those that maybe 'const' was a poor choice of key word that wasn't specific enough (some argue it should mean "cannot change value", and others are fine with "cannot be reassigned"). Was there a better key word that could have chosen to add to es6 if David's intention (don't change the value) was different than the actual implementation (don't reassign)? I assume this is the crux of David's regret.
No, the crux of the regret is that it became a debate to begin with. And it only became a debate because there's not much value in making a distinction between variables that are reassigned or not.
I can say that I've worked in codebases that used let for everything and other codebases that tried to use const wherever possible, and the difference was meh. Use const if you want, it doesn't matter; just don't think it will actually do anything.
after learning the hard way, we got a rule on work, we can't use var or let and only const, why well, when you don't reassign variables you get code you read from top to bottom, without crazy things in loop where the code do one thing and then if something next time if some thing else then it do that.
this is hard to understand and read, making that kind of code full of bugs, so now with only const no one make that kind of crazy code, and we half the amount of bugs, and we make more features and look less in the black hole of despair.
in the start people think you can't do stuff without let, but you are wrong, you are just thinking of the wrong way to fix that problem, there is always a simple way with reduce or filter to make the loops only do one pass, you can then reduce the result again and again, so each pass will fix one of the problems you used let for.
I already don't agree on the LSD part.
Damn, your explanation with a pointer and double-pointer at 15:24 was spot on, it finally clicked with me. Before this, this whole discussion seemed like a purely cultural/philosophical debate about religion and metaphysics. It still does to me, but now I feel like I actually know what the underlying thing is
As a former C++ developer, that comparison is not great. Of course using double pointers is different than using sinlge pointers, it's more convoluted. Using variables declared with let and const is pretty simar.
They really have nothing better to do with their time than intentionally misinterpret semantics so that they can act better than everyone else
You sir have nailed it. This approach is intuitive and makes the most sense 🍻
The thing is that the argument "const is not for immutability but to prevent reassignment" only exists as a ex-post justification for the bad implementation of const in JS. In C++, const is properly implemented and absolutely nobody argues it should be only for reassignment. It actually prevents mutation (and a lot of bugs that come with it).
C++ for all its warts got many things right. Const should be default but otherwise it got const right. References and values being non-nullable by default was also right. You want null, then use a pointer. But it is opt-in. But then came Java and everyone forgot about the good things C++ had.
I'm primarily a Java dev and JS const has the same semantics as Java's final keyword. The "final" behavior should be default behavior of variables, because changing the object reference of a variable opens the door to endless possible bugs. Javascript is even more so prone to these bugs due to the global scope in browsers. I think the JS designers choosing the keyword "const", implying a constant, is the root of the confusion. But the behavior is fine and should be preferred over "let"
At 16:00 "let is **" (double pointer), he's just plain wrong. It's just like saying that "int n = 1" is a pointer because you can change it...
Scope (Public, Protected, Privated) is generally recommended to be as restricted as possible; The same rationale applies to let vs const, while not actually immutable it is still more restrictive than let; These restrictions on const result in usually only having to look for areas of modification rather than complete reassignment
Between js `const` and `let` I choose not to code in javascript.
Always great content, thanks!!!
the obvious fix is to let you have two consts to show you're super serious about how const your const is
dreamberd
in C++ you can have 4 consts `const char* const hello(const char* str) const;`
it's a multiparadigm language and the keyword is CONST not IMUT, it was never supposed to behave like IMUT, I don't know where these guys get the idea that const has to be imutable. Const means that the reference is constant. I agree with you here, LET and CONST have more communication value to us if we use const to indicate that a value is not being reassigned.
JS was mistake
JS wasn't a mistake, the mistake was people trying to take it out of it's rapid prototyping scripting box and turning it into Typescript, Node, full blown complex frameworks, basically going backwards from dumb quick language into what made it in the first place.
That's something I really like in Rust. You can redefine variables/constants (shadowing) and it's encouraged. And also constants are true constants, not constant references to something that might be mutable.
does this guy just waffle to over complicate everything ?
What this guy, Theo or the speaker
It's kinda ironic in Javascript that we use CONST but then change it's value anyway as that's the const only care for the declaration, not what's within it.
I'm sorry, how do you change a const in JS?
Makes sense to me actually. Just like you have shallow copies of arrays for a reason you have shallow const. If you want a deep copy you can just freeze it.
@@PS-dp8yg when you have another reference to the underlying data . This is also the problem if they one day change it from half-backed to the normal implementation of const so many things will break.
No, you cannot change the value.
You might be confused by the semantic.
const x = {a:1};
corresponds to
struct{int a} *const x =…; in C/C++ and some other similar languages, as opposed to
struct{int a} const *const x =…;
The “reference” (“pointer”) is indeed constant and cannot be modified, but the fields of the structure that we are pointing to are not necessarily constant.
To make them constant you would have to define the field “a” in {a:1} as a “read-only” property. Otherwise, you are defining it with the regular defaults (enumerable, writeable, configurable, etc.)
You can test the following code in JS to verify that “const” prevents you from modifying the object.
const x = {a:1};
x = {b:2};
You will get an error.
It's not ironic at all, you can't change the value
When i did Swift programming, i always used const except when i needed to reassign a variable and didn't want to toss the code into a separate function.
Looks like half of JavaScript was a mistake at this moment
All of it. All of it.
Remember prototypes? Javascript itself was a mistake. All of it is technical debt, or soon will be.
Another day learning a lot with Theo! 👏
The fact that Theo gets so passionate about const vs let is exactly what this presentation is poking fun of.
100% on board with your conventions. I have arrived at the same myself.
Having a reference to an object that lets you mutate it only under its own rules should not be controversial.
Const is a great signal to the developer to make them ask the questions:
- Is my re-assignment method inefficient?
- Is there a correct place in a lifecycle that this should be updated?
11:37 does theo not know typescript?
Yeah I asked myself the same thing. "return void" lmao
Why does the first function return Promise tho?
@@hansmeyer2@hansmeyer2 The short answer is that the return value / type is 'never' defined as opposed to being explicitly returning nothing such as with `if (condition) return;` or ending the method explicitly with an empty return. The value will be undefined whether 'never' or 'void', it's just a semantic difference and is more-or-less interchangeable.
The distinction may be due to how deterministic the code is assumed to be - we know with pretty much 100% certainty the behavior a function invoking console.log() is, but there is a possibility that the first method could never finish or throw an error (hence actually never hitting end of function, therefore never even implicitly returning). Promise.reject() returns Promise, whereas Promise.resolve() will return Promise
@@stevenbasher5363 Implicit return yields void though, and nothing is being awaited in the original function, so why not Promise?
EDIT: nvm, it's the "use server". missed that earlier in the video.
typescript has a Readonly to do what people imagine const should do
Such a joke of a language. What the fuck are we even doing here.
Yes, I agree totall. The difference between constant references, etc. has meaning.
The guy never comes up with an example which shows where const would be confusing and potentially lead to programming the wrong thing!
Syntactically I would prefer js doing something like: `let immutable myVariable = ...` (or some shorter keyword than 'immutable') as a modifier for let. Immutable function parameters would also be nice to have.
I know the debate he's going to talk about and it's a massive L take. If he's going to agree, I might just unsubscribe honestly.
Ah yeah, did so [unsubscribe] quite some time ago because of his *cataclysmic egomagalomania!* ✊🏻 🙀 😹💦
Yes, we need production-level DreamBerd! 💯!!!
From -1 all the way up to infinity! ❤
title: `const` was a mistake
duration: 31 minutes
you are perfect
Your sigh at 14:34 healed my soul.
And then you wonder why everyone laughs at web devs
I seem to have totally right to rely on your wisdom.. if i would have discovered the posts from es6 creator, i would have been hyped. Thank you for your professional yet simple moderate addressing..
true
Well, I use `const` kinda as an annotation, where I create a variable that's not meant to be replaced, e.g. the HTML element the function we're in works on. So I store the element in a `const`, to modify its attributes but not replace it as a whole as I then would stop doing stuff to the element the user sees.
I would also like to mention that TypeScript allows the declaration of actually constant arrays which can then also be used in type definitions:
const vars = ["a" ,"b", "c"] as const;
The way Kotlin handles the immutability issue is by in addition to having var (==let) and val (==const), making collections immutable _by_ _default_ . You have to go out of your way to get a mutable Array etc. That would have been a change too far for JS, but at least it's moving in the right direction by completing the set of non-mutating array operations (toSorted(), toSpliced()).
Ryan's talk was clearly intended to be humorous, especially invoking ChatGPT as an authority (given that the output was clearly edited). Not distinguishing between integrals and ref's makes it an in joke for people sufficiently knowledgable about the language. Using screaming case is a hold over from when editors lacked tooltip context to understand whether, in a language like C, the symbol was a macro or a variable. Screaming case is rarely useful beyond TOUCH_THIS_AND_DIE or UNTIL_HELL_FREEZES_OVER semantics.
Exactly, Theo, exactly! Beautifully put, it's not that "const" has a specific meaning, it's that "let" is supposed to mean something specific, i.e. reassignment. Maybe that wasn't the original creator's intention (I don't know), but it certainly makes sense.
Let's just agree that Rust provided the best solution: "let": immutable by default, "let mut": explicitly mutable, no misunderstanding possible. But "const" by default is a more than reasonable fallback.
Strong agree on basically all of this. I am very much in favor of using `const` by default and using `let` to signal that reassignment is possible. And I'll use screaming case to define what you call "true constants" here.
But, also, Records and Tuples are currently late-ish stage proposals and will hopefully soon be able to soon make creating true constants much more ergonomic. Kinda wish `const` did that by default, but... We don't live in that world.
Taking a hint from Rust here, I'd be even more happy with a way of declaring things as mutable or not from the beginning, but... It's easy enough to just know a pretty fundamental thing about JS and know `const` is about assignment rather than mutability.
Having watched the Ryan video it was amusing seeing Theo’s pre-reaction to exactly what was about to happen
You are absolutely right, I don’t understand why someone would say otherwise.
18:00 About doing those ChatGPT and other AI "gotcha" posts...
The conversations are typically salted by first prompting the the AI model to be certain way or bias it towards a viewpoint.
The actual post that is shown is done after that and is like the second or third post in the conversation.
15:25 I couldn't agree more. Even more, when you go to ANY language, even constants are mutable when you assign them mutable object/instance/structure. The original intended use seems to have been limited to immutable value which was most likely a string. Nice demo though with Object.freeze which nobody uses. Not that nobody should...
In Typescript there is a kind of "const const" when declaring an immutable array or object with the "as const". I always use it when declaring "actual constants". Typescript seems pretty aware of the problem raised with let and mutable const because when u declare a "const myArray = ['abc', 'def']" it says it's an array of strings and can be mutated. If you declare with "const myArray = ['abc', 'def'] as const", it says it's an array containing 'abc' and 'def' and you can't mutate it.
100% agree. I come from C++ and moved to frontend development and I will always default to const if I have no INTENTION to change what it points to. I use let rarely and that becomes even more rare the more we move towards fluent array transformations.
I totally agree with Theo's reaction to this take.
I recall being led to believe there was a performance win by using const due saving on GC checking or some such thing. Micro-optimization for most projects, but those sorts of things are good habits to form. I could easily be mistaken, but that's why I formed the habit.
I totally agree with this. Const should be the default, and let should only be used when reassignment is needed. Although, I do partly wish that const meant completely immutable (or have some third option)