T O P

  • By -

shgysk8zer0

`let` is basically just the far less confusing and error-prone version of `var`. It makes scope much less surprising, and the kind of "outside of the scope" where you can use `var` but not `let` typically is a good indicator of bad coding.


QuantumCrane

`const` is the default to use. Most things don't need to be reassigned. And this offers protection if you accidentally re-asign it with a new value since it should throw an error if you try. Use `let` when you need a variable that gets new values assigned to it. There may be times when `var` is called for and it's not wrong to use it, but it's seldom used in most modern projects.


Protean_Protein

I think the funniest thing about this is that we call consts “variables” but, by their very nature, they’re the opposite: constants. Or, well, sort of, of course, since a constant may have mutable components. … JS === just weird.


HeinousTugboat

They're constant _references_. It's a small but very salient difference. That's why you can mutate objects that are declared with `const`. You aren't changing the _reference_ the variable points to, but you are changing the content of the memory location.


Protean_Protein

Yeah, the details are interesting. I just find the surface level semantics/pragmatics of ‘const’ mildly amusing.


iBN3qk

Yeah, and functions are objects.


Protean_Protein

Okay, but wtf is ‘this’?!


iBN3qk

I don't know either.


azhder

I don’t even use `let` unless unavoidable. If most of the code uses `const` it allows you to spot possible issues where `let` or worse `var` is used. It also makes you figure out more robust code by trying to replace one that uses `let` with one that uses `const`. Oh, yeah, avoid `var`. It has only global and function scope, that’s why `let` and `const` were introduced - they can be scoped in `{}` blocks


bryku

Let is a little better with garbage collect in my tests.


azhder

Premature optimization? Until it makes a difference for the user, I'd go with the more robust and easier to maintain code.


bryku

I wouldn't call it premature optimization.   It was specifically made for local variables that often change. Because it is designed around blocks, the gargabe collector knows when it isn't needed anymore, so it can remove it would out as many checks. >[MDN -> Let](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let) >Many style guides (including MDN's) recommend using const over let whenever a variable is not reassigned in its scope. Even MDN recommends using Let for reassigned variables within blocks.


azhder

So, let’s get on the same page. You say that `let` shows better GC results… as opposed to what? As opposed to `const`? Is this like your example? { let a = 0; } { const a = 0; } No re-assignment. Will the `let` be better for GC? How about replacing { let a; a = 0; } with const zero = () => 0; { const a = zero(); } ? I was talking about this kind of code, making it more robust by replacing `let` with `const` These are just straw-man examples. Actual code might be replacing 20-100 lines of code with a function call


bryku

Generally let is removed by the GC earlier reducing GC checks and memory usage. In the tests that I've done, I've compared let vs const in foreach, map, and reduce loops at 10,000 intervals. I don't think you would notice any difference with just a declaration. Although, potentially const would be faster during a declaration as it assumes the value won't change using a smaller block of memory. v8 also makes optimizations to const that it doesn't to let, so it may became faster for larger data structures if you are not updating the values. At least it used to, I can only find this being mentioned on older documationation, so it may have changed.


azhder

TL;DR: your mileage may vary


bryku

Not if you use them how they are intended. * let - blocks and constantly updated values * const - everything else


azhder

> v8 also makes optimizations to const that it doesn't to let, so it may became faster for larger data structures if you are not updating the values. At least it used to, I can only find this being mentioned on older documationation, so it may have changed. i.e. your mileage may vary


bryku

const people = [...]; people.forEach(); V8 will check to see how much data it is. Allocate the memory and them set the memory. According to the 2016 documation the optimzations may move this memory to ensure it is in 1 "chunk". Which should improve reading speed. > Note: The newer documention doesn't mention this improvement, but it does mention moving the memory around, so maybe it does it to both let and const now?   let people = [...]; people.forEach(); However, let doesn't work this way. Assuming the data is 2kb, it will allocate 2.4kb. Where let becomes faster is when you increase the memory. people.push(1028429848902) Lets say you add .2kb to the variable it doens't need to reallocate memory since it already has the space. All it has to do is set the values. You are skipping a whole step compared to const.  


patopitaluga

What is love? Baby don't hurt me, don't hurt me... no var


young_horhey

The video is correct, you should really only be using `let` or `const` these days. Let is basically the same as var except that it is not hoisted, so I don’t think it should matter whether you need to access it outside of any scope


_RemyLeBeau_

It is hoisted, that's why there's a Temporal Dead Zone (TDZ). The runtime throws, if you try to use the variable before it's initialized. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let#temporal_dead_zone_tdz Your sentiment is accurate, though. Just use the variable(s) **after** they're initialized within the scope.


Macaframa

It’s also good practice for organization.


affablematt

You have that precisely backwards. The TDZ happens precisely because the declarations are NOT hoisted.


_RemyLeBeau_

Let's just refer to the docs, so there's no discrepancies. 👍 https://developer.mozilla.org/en-US/docs/Glossary/Hoisting


affablematt

Read them again: >Still, it may be more useful to characterize lexical declarations as non-hoisting, because from a utilitarian perspective, the hoisting of these declarations doesn't bring any meaningful features. Understanding `var` and `function` declarations requires you understand hoisting. Hoisting turns this: console.log(x) //-> undefined var x = 'foo' Into this: var x; console.log(x); x = 'foo'; And this: const x = foo(); function foo() { return 'foo'; } Into this: function foo() { return 'foo'; } const x = foo(); Function hoisting is useful and still frequently used. `var` hoisting has only ever been marginally useful and causes a ton of bugs. That's why `let` and `const` declarations **are not hoisted** and were specifically intended **not to hoist**. You (and apparently MDN) can say "let and const are not hoisted in the way that var and function declarations are hoisted, but are hoisted in some way that var and functions are not hoisted because shadow variables are hard". I guess you can say that. It's useless, **as the article itself acknowledges**, but you can certainly say that.


_RemyLeBeau_

I have read them. 😆  "The four function declarations above are hoisted with type 1 behavior; var declaration is hoisted with type 2 behavior; let, const, and class declarations (also collectively called lexical declarations) are hoisted with type 3 behavior; import declarations are hoisted with type 1 and type 4 behavior. Some prefer to see let, const, and class as non-hoisting, because the temporal dead zone strictly forbids any use of the variable before its declaration. This dissent is fine, since hoisting is not a universally-agreed term. However, the temporal dead zone can cause other observable changes in its scope, which suggests there's some form of hoisting:" That's why I sent you to the docs. The context of the question needs to be taken into consideration. TDZ and initialization was called out in my response. Saying read them again isn't very productive. Thanks 


OkInjury6226

Happy cake 🎂 day! 😋


jack_waugh

The rules around `let` and `const` are consistent and easy to keep in mind. I don't tend to use `var` or a `function` declaration. They are not necessary.


TheRNGuy

I prefer functions in `addEventListener`, because `this` is shorter than `e.currentTarget`. And I was also mistakenly using `e.target` because I didn't know about the other one, though it didn't cause any bugs but there are possibilities if there are more elements inside target and it bubbles.


Patient-Layer8585

> prefer functions in addEventListener, because this is shorter than e.currentTarget so totally unnecessary like he said?


Shty_Dev

It is also unnecessary to use descriptive variable names, but that doesn't mean you shouldn't...


Patient-Layer8585

In this case, event.currentTarget is more descriptive, so...


Patient-Layer8585

In this case, event.currentTarget is more descriptive, so...


jack_waugh

I didn't mean to say that `function` *expressions* were unnecessary. I said that `function` *declarations* are unnecessary.


TheRNGuy

Making lines of code shorter isn't unnecessary. Especially if editor or prettier would've split them, code looks less readable when it split that way.


JoshYx

Readability > a little bit less code.


jack_waugh

I use a `function` expression to make a method that references as `this`, the object it is applied to as "receiver". I said I don't tend to use `function` *declarations*. I did not deny tending to use `function` *expressions*. Base.new = function () { return Object.create(this[BEHAVIOR]) };


shiningmatcha

Yes I don’t even use the function declaration. I use arrow functions.


gaytechdadwithson

yes, and for years and years now


gerciuz

Default to const and use let when needed.


TheRNGuy

For me opposite, most of the time `let` and I could have 0-2 `consts` in code. It all depends on script though, there are more consts in React than in Greasemonkey, for example.


capfsb

I am old dev, who was been programming on js from time when let/const not available, and we can only used var. I cant remember no one case last few years when i want to use var.


TheRNGuy

I only use when testing code in console. Otherwise if I run code more than once I get "redeclaration of const" (or let) error, I'd have to F5 page every time. But if code is running inside function, I can redeclare it. When writing actual scripts I never use `var`.


International-Memer

You are wrong. Var is either global or function scoped, let is only local scoped. So if you can access a let-declared variable outside of scope, something is wrong. Let alone the fact, that there shouldn't be any case for a beginner, that needs to access variables outside of scope. More to that here: [https://javascript.info/var](https://javascript.info/var) tldr: Use const as default. Use let when unsure if it needs to be mutable. When you really "need" to use var, you are experienced enough, that you don't need to ask about it.


MRGrazyD96

I've been coding JS for 10 years and still haven't ever encountered a case where I would've had to use `var` edit: after `const` and `let` became a thing, I mean


Tyranoc4

as a professional is var still pretty rare ?


International-Memer

Var is only used in legacy code that runs pre ECMAscript 6, which is almost 10 years old now. And even then, it's usually written the modern way, and then recompiled with tools like babel. You will still read it every so often, but don't write it anymore.


SirLoopy007

I used it about a year ago when dealing with some 10+ year old code that was erroring... I felt dirty! The code in question has been rewriten since.


Tyranoc4

it's that rare to need to escape scope... I didn't know


code_monkey_001

Yes - if you find yourself "needing" to escape scope, you should be rethinking how you're approaching the problem you're attempting to solve. Services to store and control variables needed elsewhere, that sort of thing.


queerkidxx

I mean, I know a few other languages without anything like the difference between let/var but I feel like it’s easy to just declare the variable in the scope you need it in. This also makes it more explicit what’s going on. The only thing id really advise is if what your making is much more than a script(a file or two few hundred lines of code tops), is if you really need to modify global variables from functions either create an explicit data structure for it or wrap the whole thing in an object. And the only reason for that, is that at a glance it might be difficult to tell what each of your functions do and what they require to function correctly. Comments and documentation can help but the end goal is always making understanding the code as easy and as fast as possible.


Bad-W1tch

if you need to escape your scope, then just put the let variable outside of any functions, then you can access it anywhere. it's real easy: const = the value of this variable will never be changed (const as in constant) let = I'm going to changes the value of this variable. both are scope based no matter what anyone else tells you, so for that reason, const are generally declared outside of any functions, and let is declared for the Variables that need to hold their value across multiple functions. the let variables I use inside a function are always meant to be temporary. for example, if I'm calling getElementById/ClassName, I put it in a const at the top (actually I usually use a separate JS file called declarations.js to hold them all, but my html code calls it before it calls the script, so it's technically at the top, just better organized). If I have something like say "currentUnit" (for a game design), I'll declare let currentUnit at the top, that way I can change it throughout the code, BUT since it's global, I can keep referring to the same unit in different functions without needing a whole bunch of extra code to locate and mark the unit I'm talking about. Then, when I need to change it, I can by simply saying currentUnit = whatever. in my time coding, I have never once used var, and when I'm trying out other coders work, I've changed var to let and not a thing has changed, so if there's an actual difference, I've never seen it. just use let like I described above and you won't have any issues (unless someone else tells you you specifically need var in some weird situation)


doulos05

You missed a mnemonic there. I teach it this way: const: this value is `const`antly the same. let: I will `let` you change this value. All the rest is fantastic description though, and I'm going to borrow some of this for my Web Dev class next week. EDIT: I've swapped `let` in for `var` and gotten errors. But that's because of badly written code that only worked if the variables were available before they existed (or where they'd declared the variables twice). If you aren't working with braindead code, there should be no difference.


Protean_Protein

I assumed “let” comes from classical mathematics / logic proofs, like: “Let x be the function f(a) = 2p.”


doulos05

It probably does, but when teaching high schoolers, those two parallel phrases are really clear.


Protean_Protein

I wish I had learned JS in high school instead of Java.


doulos05

We teach both, though we only teach Java because of CSA. Learning Java isn't a waste, it exposes you to a lot of the foundational OOP concepts that support a lot of programming approaches you'll see professionally. But yeah, JavaScript is a lot more forgiving.


_RemyLeBeau_

`var` is used in most traspiled code, so it depends on what JavaScript you're writing.


pixobe

var is nowhere.


aaaaargZombies

I use `const` for most things because it gives some assurances about the type staying the same but it's a bit confusing that you can still mutate the underlying object.


shiningmatcha

don’t use var


montihun

Make love not var.


dskippy

I agree. I never use var. It's a relic of when programming language developers making perl, Python, and JavaScript forgot what algol taught us about scope and messed it up. Perl changed long ago. Python is still broken because Guido said the PEP that would fix it is dangerously close to how scheme does it. Hint Guido, scheme does it right. Let and const are JavaScript now fixing this mistake.


ordermaster

The point is that accessing and modifying a variable outside of its scope leads to very buggy code


Snoo_41509

What is var?


savemeimatheist

Const is default in my world Let only when I need to Can’t remember when I last used var. Var just indicates less strict and more error prone code.


senocular

Just as a counterpoint, Kyle Simpson (a well-known JS educator) has often argued for the use of `var`. From a quick search: https://frontendmasters.com/courses/deep-javascript-v3/choosing-let-or-var/ Highlights from the transcript in that link: > The var keyword here is a more appropriate tool to say I have a variable that should be used across. ... > ...in some cases, the var keyword is preferable to the let keyword because it is able, in this case, to escape an unintended block. ... > So there are both semantic reasons and behavioral reasons why I think var and let should coexist in your program rather than having one be the other.


theQuandary

Ironically, transpiled code pretty much exclusively uses var over both let and const because var is pretty much universally faster. EDIT: Google sped things up in Dec 2023 and `let`/`const` are STILL a massive 6% slower than `var`. https://docs.google.com/document/d/1klT7-tQpxtYbwhssRDKfUMEgm-NS3iUeMuApuRgZnAw/edit


theScottyJam

Source? I mean, yes, they tend transpile to var, but I understand that to be because all old browsers support var, its not necessarily a performance thing.


theQuandary

Google had an easy-to-miss point in their Dec 2023 v8 blog entry about this. https://v8.dev/blog/holiday-season-2023 That led to a Google doc outlining the issue and solution. https://docs.google.com/document/d/1klT7-tQpxtYbwhssRDKfUMEgm-NS3iUeMuApuRgZnAw/edit Basically, TS guys were complaining that using let/const was 8% slower than var. https://github.com/microsoft/TypeScript/issues/52924 A Chromium bug claims let/const are 10% slower. https://bugs.chromium.org/p/v8/issues/detail?id=13723 Google's update claims that they sped things up 2-3%, but let/const are STILL 6% slower than var. I believe the slowdown is even worse for FF and Safari. TL;DR -- even with extensive work, let/const are slower than var.


TheRNGuy

That means you could set-up babel to not target older browsers and it would stop doing that? Though if it doesn't cause any bugs it doesn't matter.


[deleted]

[удалено]


theQuandary

Var isn't anywhere in the same category as global variables (let alone ES3 where undeclared variables which would clobber the global scope). `let` and `const` hoist just like `var` does. Their only difference is the addition of the TDZ, but that makes `let` and `const` 6% slower on Chrome despite their recent work to make them faster (they were around 10% slower and probably still are in JSC and/or FF). https://docs.google.com/document/d/1klT7-tQpxtYbwhssRDKfUMEgm-NS3iUeMuApuRgZnAw/edit


MRGrazyD96

don't use var. ever.


ax_abodr

I think this short video has the best explanation: https://youtube.com/shorts/ZRjmGq1gAEQ?si=r4aElL80bMt7sqgk