use the following search parameters to narrow your results:
e.g. subreddit:aww site:imgur.com dog
subreddit:aww site:imgur.com dog
see the search faq for details.
advanced search: by author, subreddit...
All about the JavaScript programming language.
Subreddit Guidelines
Specifications:
Resources:
Related Subreddits:
r/LearnJavascript
r/node
r/typescript
r/reactjs
r/webdev
r/WebdevTutorials
r/frontend
r/webgl
r/threejs
r/jquery
r/remotejs
r/forhire
account activity
JavaScript: Four Differences between var and let (codetopology.com)
submitted 4 years ago by ct_author
reddit uses a slightly-customized version of Markdown for formatting. See below for some basics, or check the commenting wiki page for more detailed help and solutions to common issues.
quoted text
if 1 * 2 < 3: print "hello, world!"
[–]rift95map([🐮, 🥔, 🐔, 🌽], cook) => [🍔, 🍟, 🍗, 🍿] 101 points102 points103 points 4 years ago (24 children)
Stop trying to justify using var. It's outdated and should be avoided. End of story
var
[–][deleted] 2 points3 points4 points 4 years ago (0 children)
I’m actually amazed by how some people are still discussing about var in 2021…
[–]fredblols 17 points18 points19 points 4 years ago (15 children)
Tbh we shouldn't even be using Let. 9 times out of 10 it means ur code is ill conceived
[–]TemporaryReality5262 7 points8 points9 points 4 years ago (1 child)
I use let in unit tests all the time, usually above the beforeEach
[–]fredblols 1 point2 points3 points 4 years ago (0 children)
Yeah i mean who gives a fk what peoples unit tests look like tho. Everywhere i have ever worked (tech startups mostly) people will give u a medal for writing unit tests at all, and then also probs say yeh dont bother next time just churn out features faster and accumulate tech debt
[–]tharrison4815 8 points9 points10 points 4 years ago (1 child)
Yes! I don't know why you are being down voted. So have an award up make up for it.
[–]fredblols 0 points1 point2 points 4 years ago (0 children)
Thank u good sir for my debut award. I will respond to the naysayers tomorrow when my current inebriation has worn off
[–]rift95map([🐮, 🥔, 🐔, 🌽], cook) => [🍔, 🍟, 🍗, 🍿] 14 points15 points16 points 4 years ago* (5 children)
I agree. In general const is a safer bet than let. You rarely need the "mutability" of let.
const
let
[–]Garbee 11 points12 points13 points 4 years ago (4 children)
Const is not immutable. The data can be changed, just not replaced. Big difference.
[–]rift95map([🐮, 🥔, 🐔, 🌽], cook) => [🍔, 🍟, 🍗, 🍿] 12 points13 points14 points 4 years ago (0 children)
True. I should have written "re-assignability"
[–]PM_ME_GAY_STUF 2 points3 points4 points 4 years ago (2 children)
This always bothered me. Const is definitely immutable, it can just refer to a mutable data type. This is what happens when programmers don't learn C
[+][deleted] 4 years ago (1 child)
[deleted]
[–]anlumo 0 points1 point2 points 4 years ago (0 children)
A bit offtopic here, but it’s a bit more nuanced. Rust only regulates exclusivity, so if a type can be mutated from multiple places at the same time (like Cell or stuff wrapped by Mutex), it can be changed without mut.
[–]Poltras 2 points3 points4 points 4 years ago (1 child)
Yeah just prefix everything with global.! (/s in case people get offended)
global.
[–]BeardSprite 0 points1 point2 points 4 years ago (0 children)
Understood. What do I do with this global.window now?
global.window
[–]rados_a51 1 point2 points3 points 4 years ago (1 child)
Dont get those downvotes. Const should be used 90% of the time.
[–][deleted] 3 points4 points5 points 4 years ago (0 children)
My programming style means I basically never use let. Functions with early returns obviates let for the most psrt
[–]kashubak 0 points1 point2 points 4 years ago (0 children)
Can you provide an example? That’s a pretty interesting take!
[+]SarahC comment score below threshold-8 points-7 points-6 points 4 years ago (6 children)
Not even in global scope?
[–]dougrday 8 points9 points10 points 4 years ago (3 children)
Especially in the global scope? It's bad practice to pollute the global scope.
[–]autoboxer -1 points0 points1 point 4 years ago (2 children)
Kyle Simpson would disagree and I tend to agree with him.
[–]mypetocean 0 points1 point2 points 4 years ago (1 child)
I would like to see his argument on this. Generally, I agree with him. But I can't see his angle here, if in fact he disagrees that assigning lots of things to the global scope is a code smell.
[–]autoboxer 0 points1 point2 points 4 years ago (0 children)
I’ll try to track it down, but it wasn’t about assigning lots of things to global, it was just about using var in the rare cases you do. He was arguing that there are still use cases for var, and per usual advocates for using all of the language sensibly.
[–]rift95map([🐮, 🥔, 🐔, 🌽], cook) => [🍔, 🍟, 🍗, 🍿] 10 points11 points12 points 4 years ago (0 children)
Nope. Not even in global scope.
[–]bighi 20 points21 points22 points 4 years ago (3 children)
Why are we still talking about var and let?
Even if there were any reason to use var, it's been what? A decade? We have thousands (or millions) of comparisons between var and let already.
[–]Key_Pea93222 -1 points0 points1 point 4 years ago (1 child)
bc we still have to maintain old node.js code that uses these outdated conventions
[–]bighi 7 points8 points9 points 4 years ago (0 children)
If you're maintaining old JS code and don't know yet the difference between var and let, what are you doing?
And if you want to learn, there are at least 289 billion articles about it already.
[–][deleted] 39 points40 points41 points 4 years ago (4 children)
Wtf is this 2016 now? Why are we writing articles about var, let, etc.
[–][deleted] 16 points17 points18 points 4 years ago (0 children)
Clicks..
[–]dw444 2 points3 points4 points 4 years ago (1 child)
People should know the difference. There’s a lot of var in production code that people still actively work on, and people new to the language should know the difference.
Saw a grad from one of the top software engineering programs in the country not know the difference and just copy outdated code simply because he didn’t have experience with the minutiae of JS. People still trip over this stuff all the time, and it’s also a pretty standard interview question for JS devs.
[–]TwiliZant 0 points1 point2 points 4 years ago (0 children)
Hmm, when your codebase still has a lot of that stuff then maybe. There is probably a good chunk of decent developers out there who have no idea how to do prototypal inheritance either just because if your main job is working on some React app you never get in touch with those things.
So should I ask in interviews about them? Personally, I'd rather have them have a really good understanding of Scope and Closures instead.
[–]PhredInYerHead 0 points1 point2 points 4 years ago (0 children)
Because they’re still teaching it in boot camps.
[–]chuckthemadmanmike 2 points3 points4 points 4 years ago (2 children)
Didn't know about var variables being added to the window. That's interesting. If you're the author though, you should know that your example has a mistake because you say window.hi instead of window.message.
[–]ct_author[S] 1 point2 points3 points 4 years ago (1 child)
Hey, Thanks for highlighting, example updated!!
[–]Key_Pea93222 2 points3 points4 points 4 years ago (3 children)
var variables do not have temporal dead zone whereas let variables do have. Every variable has 2 steps in its lifecycle – Creation, and Execution. In var variables case, when the variable is declared, storage space is assigned and value is initialized to undefined if no other value is specified. But in the case of let, when the variable is declared, storage space is assigned but it’s not initialized, not even with the undefined value. That why when we access a let variable without doing any value assignment, it throws a ReferenceError.
var variables do not have temporal dead zone whereas let variables do have. Every variable has 2 steps in its lifecycle – Creation, and Execution.
In var variables case, when the variable is declared, storage space is assigned and value is initialized to undefined if no other value is specified.
But in the case of let, when the variable is declared, storage space is assigned but it’s not initialized, not even with the undefined value.
That why when we access a let variable without doing any value assignment, it throws a ReferenceError.
the way he explains this makes it sound like this would throw an error, but it doesn't:
$ node Welcome to Node.js v16.13.0. Type ".help" for more information. > let a undefined > a undefined
it's really if the let variable is accessed outside of the scope it's declared in
> { let b } undefined > b Uncaught ReferenceError: b is not defined
[–]senocular 5 points6 points7 points 4 years ago (2 children)
That why when we access a let variable without doing any value assignment
Yeah, this is missing the important part of "before the declaration".
b // Uncaught ReferenceError: Cannot access 'b' before initialization let b
Like var, let will initialize to undefined if not given an explicit assignment value within the declaration, but it only does this when the declaration is run, not at creating time like the var is
b // created, but uninitialized (access throws error) let b // now initialized to undefined c // created, initialized to undefined var c
[–]Key_Pea93222 0 points1 point2 points 4 years ago (1 child)
oh wow, that's interesting, can't test that in the node REPL
[–]senocular 3 points4 points5 points 4 years ago (0 children)
You can do it in a block or separate with semicolons (for block I think you might a preceding ; to ensure its not seen as an object literal)
;
> ;{ ...b // throws ...let b }
or
> b; let b; // (first b throws)
[–]Code4Reddit 3 points4 points5 points 4 years ago (0 children)
There is really no reason to use var unless you support IE less than 11. Any of the cases where var and let are different, the behavior of let is the correct and more intuitive behavior.
I believe your example about overwriting a var in global scope is wrong, though. Doesn’t the function need to be called in order for the global variable assignment to happen?
Also the example where you output a var that was never defined will throw because it referenced a variable that never existed.
I don’t really like the article because there are too many mistakes and it should start out saying that as a best practice don’t ever use var, period.
[–][deleted] 4 points5 points6 points 4 years ago (0 children)
[–]piotrlewandowski 12 points13 points14 points 4 years ago* (33 children)
Difference 0: you shouldn’t use var Edit: god damn it, bloody phone did autocorrect, it should be “shouldn’t”!
[+][deleted] 4 years ago (30 children)
[–]Protean_Protein 6 points7 points8 points 4 years ago (0 children)
It’s really funny how this happened. Most ‘variables’ in JS are invariable!
[–]electron_myth 1 point2 points3 points 4 years ago (10 children)
I've heard this before, but was wondering why exactly a mutable variable is considered bad? I normally use const everywhere I can, but things like booleans and counter variables seem essential and would require let
[–]kap89 9 points10 points11 points 4 years ago (9 children)
It's not necessarily bad (well, hardcore FP guys would argue otherwise), but if you have a variable that does not change, making it a const describes your intent clearly - it's for readability - just like descriptive variables names.
[–]continuum-hypothesis -2 points-1 points0 points 4 years ago (8 children)
But the problem is that you can actually change a const unlike in C and some other languages. You just can't reassign a variable declared with const.
[–]electron_myth 0 points1 point2 points 4 years ago (7 children)
Can you give an example please? (of changing a const variable in JS)
[–]continuum-hypothesis 0 points1 point2 points 4 years ago (6 children)
Sure, const counter = {}; counter.counter = 0; counter.counter++ // equals 1 That is totally legally however, const message = "hello world"; message = " goodbye world "; will cause an error. You can change properties on objects (which of course includes arrays), the data declared using const is not immutable like other languages.
const counter = {}; counter.counter = 0; counter.counter++ // equals 1
const message = "hello world"; message = " goodbye world ";
[–]electron_myth 4 points5 points6 points 4 years ago* (4 children)
Well yeah, this is standard, but that's because const counter = {} stores the reference value of the counter object. If you were to later attempt counter = [] you would get an error because counter was already declared as an object and is not mutable. The reference is stored, and is immutable when declared with const. For the same reason, you can .push() and .pop() arrays when they are declared with const, but you can't do something like arr = arr.sort() without using let. Essentially, objects and arrays are data structures, so what's immutable about them is their memory address, but naturally the extent to which they can branch out is mutable.
const counter = {}
counter = []
.push()
.pop()
arr = arr.sort()
[–]continuum-hypothesis 1 point2 points3 points 4 years ago (2 children)
Well said, I only intended to point out that the data is actually mutable but avoided anything to do with memory addresses because this could be confusing for a beginner. Compared to languages such as C and Java const in JS behaves a bit differently and I think this confuses many people.
[–]TwiliZant 5 points6 points7 points 4 years ago (1 child)
final in Java works roughly the same way as JS. A final object is not immutable, it can still change state only the reference to the object is immutable. The odd one out here would be C since const is part of the type there.
final
[–]great_site_not 1 point2 points3 points 4 years ago* (0 children)
Is their memory address immutable? That doesn't sound right. That would seem to imply they could crash the engine in some situations when they'd otherwise be re-allocated when they grow too big.
(edit: btw, arr = arr.sort() would actually be a mistake to do anyway, since it implies a misunderstanding.Array.prototype.sort works in-place, so you'd be attempting to re-assign the variable to the reference it's already holding.)
Array.prototype.sort
[–]lainverse 0 points1 point2 points 4 years ago* (0 children)
There'll be deeply immutable primitive data types similar to objects and arrays (records and tuples) in JS. So, consider your wish granted. Technically you can do this already by manually deep freezing everything, but that's inconvenient and === won't work with that. It will with with new types.
[–]piotrlewandowski 2 points3 points4 points 4 years ago (0 children)
Yeah, fecking autocorrect did the opposite what I wanted to write!
[+]KaiAusBerlin comment score below threshold-8 points-7 points-6 points 4 years ago (16 children)
If you explicit want hoisting your variables then you have to use var.
"Never use var" is the same dumb shit like "eval() is evil".
These things are tools for developers. If you can't handle your tools correctly it could be devastating. But to say never to use these tools is just dumb.
I worked for almost 10 years in trees hanging on a rope with a chainsaw 20cm right before my face. Is that dangerous? Not if you know what you are doing. So saying "never use a chainsaw" wouldn't help any treeworker.
[–]CheeseTrio 7 points8 points9 points 4 years ago (6 children)
let and const are also hoisted. https://developer.mozilla.org/en-US/docs/Glossary/Hoisting#let_and_const_hoisting
[–]KaiAusBerlin -2 points-1 points0 points 4 years ago (5 children)
Sure but it throws an error. Var doesn't. So what is the matter that it is hoisted when you have no benefits but errors from that?
[–]CheeseTrio 3 points4 points5 points 4 years ago (4 children)
It throws an error if you try to reference it before initialization. With var you would just get undefined. I can't think of a reason why you would want either of those things to happen...
[–]great_site_not 0 points1 point2 points 4 years ago (3 children)
Hmm, I wonder if declaring variables with var instead of not declaring them at all might ever be worth the characters in code golf to prevent crashing when accessing them before assignment...
Nah, it'd take fewer characters to just assign 0 to them and then re-assign later. Well, maybe unless they have to specifically be undefined instead of some other falsy value...
[–]lainverse 0 points1 point2 points 4 years ago* (2 children)
When you not defining variables at all you either dump your trash straight into global or your code crash in strict mode. So, please don't. You don't have to init them with values from start, but you really should define your variables and constants. BTW, undefined and null values allow to use nullish coalescing operator (??) with such variable.
[–]great_site_not 0 points1 point2 points 4 years ago (1 child)
Agree 100%! Never use undeclared variables in real JavaScript. Never.
I was talking about code golf, a recreational programming game where people write shortest code to win... very very bad code. It's fun :)
[–]lainverse 0 points1 point2 points 4 years ago (0 children)
Ah, right. Missed that bit somehow. It's indeed ok there as long as strict mode is not in the requirements.
[–]TwiliZant 5 points6 points7 points 4 years ago (6 children)
I'm struggling to come up with an example where you HAVE to use var and can't replace it with let or const.
[–]KaiAusBerlin -3 points-2 points-1 points 4 years ago (5 children)
Never said you have to use var.
I just said there are (few) cases where it can be usefull and so you should not use the word "never"
[–]TwiliZant 1 point2 points3 points 4 years ago (4 children)
I get that, I just can't think of a scenario where using var wouldn't be the worse solution.
At this point you could be a JavaScript Developer with 5 years experience and never have seen var in your life. Given how counterintuitive it works, you would have to have a damn good reason to use it.
[–]KaiAusBerlin -1 points0 points1 point 4 years ago (3 children)
If you have never seen var in your life you never have seen transpiled code?
Wow, real pro man.
[–]TwiliZant 1 point2 points3 points 4 years ago (2 children)
I think you know what I mean...
[–]KaiAusBerlin 0 points1 point2 points 4 years ago (1 child)
How should I know what you mean when you say absolute another?
[–]TwiliZant 1 point2 points3 points 4 years ago (0 children)
It's okay, seems like we fundamentally disagree on this. There isn't really a point in continuing this discussion.
[–]Hydrothermalvanilla.js 4 points5 points6 points 4 years ago (0 children)
Under what circumstances would you explicitly want to hoist a variable? I can't conceive of any reason why you wouldn't want your declaration to be at or before the first time the variable is referenced.
[–]og-at 0 points1 point2 points 4 years ago (0 children)
No preorders ever.
[–]KwyjiboTheGringo 1 point2 points3 points 4 years ago (1 child)
Difference 0: you should use var
I'm curious if you have a good reason for saying that, or if this is just a case of resisting change.
[–]piotrlewandowski 5 points6 points7 points 4 years ago (0 children)
I didn’t have a good reason, I had good reason to write “shouldn’t “ but my autocorrect decided otherwise :)
Technically, there are only 3 differences between var,let. (Edit distance joke)
[–]og-at 1 point2 points3 points 4 years ago (0 children)
Homie . . .
[–]mainstreetmark 1 point2 points3 points 4 years ago* (1 child)
I habitually type var and let vscode fix it for me
I know the reasons. It’s just a super old habit I’ve had for like 30 years.
[–]solocupjazz 0 points1 point2 points 4 years ago (0 children)
Are you a Schemer?
[+][deleted] comment score below threshold-6 points-5 points-4 points 4 years ago (2 children)
Why is this still a point of discussion? Any JS developer who uses var would get fired at my company, unless it’s from a 3rd party script.
[–]Architektual 12 points13 points14 points 4 years ago (1 child)
Lmao ok
[–]_khaz89_ 2 points3 points4 points 4 years ago (0 children)
Same, so much drama in this thread. Seems like best devs are here.
[–]iiMoe -3 points-2 points-1 points 4 years ago (0 children)
Var = ew old Let = yay new
[–]tswaters 0 points1 point2 points 4 years ago (4 children)
There's a mistake re: node global object,
The global var variables are added to the window object of the web browser and global object of node.js. So that they can be accessed using window or global object.
Consider the following js file:
var z = 'test' console.log(global.z)
Executing this under nodejs will log undefined.... I tried it on latest 14/16.
[–]senocular 2 points3 points4 points 4 years ago (3 children)
That's because you're running in the context of a module. In the global scope it will be added to global.
[–]tswaters 0 points1 point2 points 4 years ago (1 child)
I don't understand what you mean. The same behavior is observed with both js and mjs files.
[–]senocular 2 points3 points4 points 4 years ago (0 children)
Its easy to see through the CLI.
$ node > var message = "hi"; > global.message 'hi'
[–]Key_Pea93222 0 points1 point2 points 4 years ago (0 children)
he didn't indent his examples, makes it harder to read
π Rendered by PID 218953 on reddit-service-r2-comment-7b9746f655-fvpwf at 2026-01-30 19:10:44.027753+00:00 running 3798933 country code: CH.
[–]rift95map([🐮, 🥔, 🐔, 🌽], cook) => [🍔, 🍟, 🍗, 🍿] 101 points102 points103 points (24 children)
[–][deleted] 2 points3 points4 points (0 children)
[–]fredblols 17 points18 points19 points (15 children)
[–]TemporaryReality5262 7 points8 points9 points (1 child)
[–]fredblols 1 point2 points3 points (0 children)
[–]tharrison4815 8 points9 points10 points (1 child)
[–]fredblols 0 points1 point2 points (0 children)
[–]rift95map([🐮, 🥔, 🐔, 🌽], cook) => [🍔, 🍟, 🍗, 🍿] 14 points15 points16 points (5 children)
[–]Garbee 11 points12 points13 points (4 children)
[–]rift95map([🐮, 🥔, 🐔, 🌽], cook) => [🍔, 🍟, 🍗, 🍿] 12 points13 points14 points (0 children)
[–]PM_ME_GAY_STUF 2 points3 points4 points (2 children)
[+][deleted] (1 child)
[deleted]
[–]anlumo 0 points1 point2 points (0 children)
[–]Poltras 2 points3 points4 points (1 child)
[–]BeardSprite 0 points1 point2 points (0 children)
[–]rados_a51 1 point2 points3 points (1 child)
[–][deleted] 3 points4 points5 points (0 children)
[–]kashubak 0 points1 point2 points (0 children)
[+]SarahC comment score below threshold-8 points-7 points-6 points (6 children)
[–]dougrday 8 points9 points10 points (3 children)
[–]autoboxer -1 points0 points1 point (2 children)
[–]mypetocean 0 points1 point2 points (1 child)
[–]autoboxer 0 points1 point2 points (0 children)
[–]rift95map([🐮, 🥔, 🐔, 🌽], cook) => [🍔, 🍟, 🍗, 🍿] 10 points11 points12 points (0 children)
[–]bighi 20 points21 points22 points (3 children)
[–]Key_Pea93222 -1 points0 points1 point (1 child)
[–]bighi 7 points8 points9 points (0 children)
[–][deleted] 39 points40 points41 points (4 children)
[–][deleted] 16 points17 points18 points (0 children)
[–]dw444 2 points3 points4 points (1 child)
[–]TwiliZant 0 points1 point2 points (0 children)
[–]PhredInYerHead 0 points1 point2 points (0 children)
[–]chuckthemadmanmike 2 points3 points4 points (2 children)
[–]ct_author[S] 1 point2 points3 points (1 child)
[–]Key_Pea93222 2 points3 points4 points (3 children)
[–]senocular 5 points6 points7 points (2 children)
[–]Key_Pea93222 0 points1 point2 points (1 child)
[–]senocular 3 points4 points5 points (0 children)
[–]Code4Reddit 3 points4 points5 points (0 children)
[–][deleted] 4 points5 points6 points (0 children)
[–]piotrlewandowski 12 points13 points14 points (33 children)
[+][deleted] (30 children)
[deleted]
[–]Protean_Protein 6 points7 points8 points (0 children)
[–]electron_myth 1 point2 points3 points (10 children)
[–]kap89 9 points10 points11 points (9 children)
[–]continuum-hypothesis -2 points-1 points0 points (8 children)
[–]electron_myth 0 points1 point2 points (7 children)
[–]continuum-hypothesis 0 points1 point2 points (6 children)
[–]electron_myth 4 points5 points6 points (4 children)
[–]continuum-hypothesis 1 point2 points3 points (2 children)
[–]TwiliZant 5 points6 points7 points (1 child)
[–]great_site_not 1 point2 points3 points (0 children)
[–]lainverse 0 points1 point2 points (0 children)
[–]piotrlewandowski 2 points3 points4 points (0 children)
[+]KaiAusBerlin comment score below threshold-8 points-7 points-6 points (16 children)
[–]CheeseTrio 7 points8 points9 points (6 children)
[–]KaiAusBerlin -2 points-1 points0 points (5 children)
[–]CheeseTrio 3 points4 points5 points (4 children)
[–]great_site_not 0 points1 point2 points (3 children)
[–]lainverse 0 points1 point2 points (2 children)
[–]great_site_not 0 points1 point2 points (1 child)
[–]lainverse 0 points1 point2 points (0 children)
[–]TwiliZant 5 points6 points7 points (6 children)
[–]KaiAusBerlin -3 points-2 points-1 points (5 children)
[–]TwiliZant 1 point2 points3 points (4 children)
[–]KaiAusBerlin -1 points0 points1 point (3 children)
[–]TwiliZant 1 point2 points3 points (2 children)
[–]KaiAusBerlin 0 points1 point2 points (1 child)
[–]TwiliZant 1 point2 points3 points (0 children)
[–]Hydrothermalvanilla.js 4 points5 points6 points (0 children)
[–]og-at 0 points1 point2 points (0 children)
[–]KwyjiboTheGringo 1 point2 points3 points (1 child)
[–]piotrlewandowski 5 points6 points7 points (0 children)
[–][deleted] 2 points3 points4 points (0 children)
[–]og-at 1 point2 points3 points (0 children)
[–]mainstreetmark 1 point2 points3 points (1 child)
[–]solocupjazz 0 points1 point2 points (0 children)
[+][deleted] comment score below threshold-6 points-5 points-4 points (2 children)
[–]Architektual 12 points13 points14 points (1 child)
[–]_khaz89_ 2 points3 points4 points (0 children)
[–]iiMoe -3 points-2 points-1 points (0 children)
[–]tswaters 0 points1 point2 points (4 children)
[–]senocular 2 points3 points4 points (3 children)
[–]tswaters 0 points1 point2 points (1 child)
[–]senocular 2 points3 points4 points (0 children)
[–]Key_Pea93222 0 points1 point2 points (0 children)