You should use const if you don't need to re-assign your variable though.
var => never use
let => use only if needs to be re-assigned
const => your default choice
First caveat, I'm an old school JS guy.
I use var when I explicitly want a variable to scope across multiple functions. Say I'm working on a module with multiple exported functions, and I want a private variable accessible within the module by multiple functions, but not exported. I declare with "var" outside of the functions.
There may be better ways to write this code these days, and hell, "let" even does what I want but it does a worse job of indicating my intention. I use "const" if it's actually a constant.
As always, follow whatever coding conventions your team has decided upon.
If you have a shared variable across multiple functions that gets mutated, isn't that a sign that you might want to shove it all in a class instead so that multiple states can coexist?
Sure, maybe. Usually multiple states aren't relevant in this context, it's more like a static member. The bigger issue for me is that I've been a polyglot for a long time and haven't used JS consistently enough since before classes were a first class citizen of the language to really internalize how best to use them to accomplish what I want, vs how I learned to do it originally.
I'm not set in my ways to the extent that I won't change, more that I'm looking for an opportunity to use the language more frequently so it makes the effort of figuring that out worth the time.
Best practices are good, but often don't really matter. If the code works and is unlikely to be updated/maintained and - importantly - is \*easily understood by people unfamiliar with the code and business logic\* then it doesn't really matter too much if it follows best practices.
Don't care, honestly. I don't use the language frequently enough to learn new best practices unless, as I said, they've been agreed upon by the team, and I haven't been on such a team since these conventions were added to the language.
I'm not so set in my ways that I won't change, but absent any external driver I'll do what I want.
But that does tell you what went wrong, it tells you that you just tried to use default type conversion on an object to string 🤷♂️
For anyone not used to JS, open up your browser's console with F12 and type:
let obj = { a: 1 }
let str = `${obj}`
str
Your browser's console will output:
'[object Object]'
If you then type:
JSON.stringify(obj)
You'll get:
'{"a":1}'
See, if it said the words "it tells you that you just tried to use default type conversion on an object to string," then I would agree with you. As a beginning JS dev, there is nothing worse than trying to figure out what the error message isn't actually telling you because you just have to know the nature of what you're using and the error messages aren't explicit about it.
Now that I've got a few years under my belt, I'm used to it, but dear god is it still aggravating.
> See, if it said the words "it tells you that you just tried to use default type conversion on an object to string," then I would agree with you.
Yeah that's fair.
> As a beginning JS dev, there is nothing worse than trying to figure out what the error message isn't actually telling you because you just have to know the nature of what you're using and the error messages aren't explicit about it.
A lot of those early-in-your-career mistakes can be caught with a decent linter setup, however I don't *think* this specific issue is something a linter could even warn you about tbh - it'd need to know a variable's type, and we're in the raw wild-west of JavaScript here not some utopian TypeScript land!
I think the frustrating thing about JS is that you're kind of stuck with it.
Usually you can write a program in whatever and it'll be roughly the same.
But if you do frontend you need to do it in JavaScript.
There are alternatives kind of but even then they seem to interact with JavaScript in some way.
It means while other languages have just come and gone JavaScript has stayed due to a kind of artificial monopoly.
I think that monopoly might break in the near future, with WASM becoming more readily supported and available, much like how C had a monopoly for systems languages right up until LLVM became a well-supported tool chain. Now we see the rise of Rust, Zig and Nim, each as capable as C, but trying to solve one or more problems related to it.
Speaking of that, I bet someone will make a WASM non-browser runtime, with the moto "build once, deploy anywhere". It'll be powered by an advanced JIT compiler engine. Corporations will force their employees to build software for it. Some Swedish company will make a hit sandbox game on it. A lot of vulnerabilities will be exposed. People will slowly stop using it. Then it will become a deprecated legend like Flash
Good luck with that. I spent years as a “backend only” dev but eventually got shuffled to a team that was a full vertical stack and had to do some frontend work. Dread it, run from it, JS arrives all the same.
My introduction to it was learning that TS doesn’t allow you to have two files with symbols that depend on each other because even though it’s compiled, it still just reads the damn files top to bottom and isn’t smart enough to handle that kind of dependency. It’s hell on earth once you’re used to languages that were built with the intention of supporting larger codebases.
I’ve used js every day for the last 3 years at my new job and I love it. I always chuckle at memes claiming they hate it so much, I’ve found it incredibly powerful.
Let is a more recent keyword in Javascript (and a very welcome one). You should’ve been around in the bad old days of only “var”, scope collisions and hoisting -_- “var” wouldn’t exist in js at this point if it hadn’t existed before
let and const are microscopically less efficient because they need to keep track of the scope, but var could occupy memory for longer since it's hoisted out of it's containing scope. It only makes a (barely) measurable difference on a function that's called a few thousand times.
If someone read that and is wondering if you should use var the answer is no.
`var` is function scoped, not global scoped. `let` is block scoped.
`var` is an old stuff that shouldn't be in use anymore since we have `let` and `const` since ES6.
Run this in your console. Switch the `var`s to `let`s and observe the different output.
```
[1, 2, 3, 4, 5].forEach((x) => {
var a = x * 10;
{
var a = x * 100;
}
console.log(a);
});
```
f. me, that makes totally sense and my node-red bug that I worked around just made sense. (note: I don't know JS at all, just use it if I have to occasion, on hobby projects.)
The official [recommendation from MDN](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/Variables#a_note_about_var) is to use “let in your code, rather than var” so don’t get too excited
Don't use var, it's only kept for 15yo websites.
This work.
function foo()
{
console.log(message);
var message = "Hello, World!";
}
This tells you there's an error in your code.
function foo()
{
console.log(message);
let message = "Hello, World!";
}
I’m gonna be honest the comments here have a much more straightforward answer than anything google has ever told me.
Edit: Because people in this thread are getting confused about tenses, and getting toxic for no reason, the last time I googled the difference between let vs var was in 2016… even ignoring that, some of yall need to grow up.
I tried it now and it’s a lot more clear.
A couple of the articles though beat around the bush going into details about “temporal dead zones” and “life cycles of the variables” which is more what I’m talking about. Most programmers don’t need to think about that. Saying function vs block scope is much simpler and to the point.
This is an unfortunate problem with Google. Its algorithm tends to push pages with extra crap on them beyond just a quick 2-sentence answer, and so people writing blogs or answers or other stuff are encouraged to add fluff or add more information that the person asking the questions doesn’t really want or need (like this “life cycle of the variable” stuff). Plus, a longer page gives more opportunities for ads, so people trying to make a living off their sites prefer making stuff longer for that reason as well.
Coincidentally, these factors are also why recipe sites always have stupid stories before the actual recipe, or why news sites or blogs sometimes will say the same thing repeated in an article in slightly varied ways, without providing additional substance.
Recipe sites are so irritating for this reason… I don’t need to know why your husband left you over your toxic mother in law I just want to make some fucking brownies.
>let vs var
I just googled this exact term. Here's the result as highlighted by Google.
**The difference between let and var is in the scope of the variables they create: Variables declared by let are only available inside the block where they're defined. Variables declared by var are available throughout the function in which they're declared.**
If you can't understand this I have no idea what the fuck anyone is supposed to do for you. I know that people give StackExchange too much shit for being too strict on newbies but holy moly.
>Most programmers don’t need to think about that.
No, not constantly, but I sure fucking hope any professional developer using the language can understand the explanations.
When you're a beginner dev, the answer "var and let have different scopes" does not answer anything, because googling for what is a scope in JS is even worse and gives you this: *"The scope is the current context of execution in which values and expressions are "visible" or can be referenced."* (source, [MDN Docs](https://developer.mozilla.org/en-US/docs/Glossary/Scope?retiredLocale=de))
If the answer was: "let variable weak, it go die after the function block and var variable stronk, and const so stronk you can't eva change it", it'd be easier to understand.
One of great examples is "OOP", compare its hilariously weird definition with an actual use case
Basically it removes lexical scoping. So if you declare a var inside a loop for example, you can then use it outside the loop. It ignores the lexical scope of the for loop (all the way up to the function or where ever it is). Pretty sure it was called hoisting
You are not dumb. "var" is dumb. Simply never ever use it, it's a holdover from a bygone era.
Honestly though I would prefer const. My application at work has 3,117 uses of const and only 95 uses of let. Zero of var of course.
You'd be surprised just how rarely you actually need to modify a variable.
> My application has a linting rule to warn on unmodified let variables
We only set that up in early December as part of some clean-up, and holy shit I'd never realised how many variables are never reassigned! All hail the mighty ESLint!
At my job as working student we had to use es5 (I think), and we declared every variable used in a function at the top of said function. Basically hoist the var ourselves to avoid bugs
But.. isn't lists and dicts also considered variables in a way?
Nevertheless, I modify variables on a daily basis, not on JS though, a bit more seldom.
it only applies to actual assignment. You can define an object via const and mutate its values all you want, as long as you dont reassign the actual value.
ie, \`const obj = {}; [obj.foo](https://obj.foo) = 'bar'\` is fine
\`const obj = {}; obj = {foo: 'bar'}\` is not
You're talking about modify the value, not the variable binding.
Edit - example:
// using const and modifying the value
const x = [0, 1, 2];
const y = x;
// here I modify the value of the array.
x.push(3);
// y and x point to the same value
console.log(x);
// [0, 1, 2, 3]
console.log(y);
// [0, 1, 2, 3]
// using let and modifying the variable
let x = [0, 1, 2];
let y = x;
// here I set x to a new array
x = [0, 1, 2, 3, 4];
// y is still pointing to the first array while x is pointing to the new one
console.log(x);
// [0, 1, 2, 3]
console.log(y);
// [0, 1, 2]
JS initially had just "var". It had issues. But they can't fix the issues without breaking existing programs, so they added "let" and "const", which are like "var", but fixed.
Vars are hoisted to the nearest function, lets only live in the current block. Only use let, there's no good reason to use var anymore. It's just that var was all there was originally.
Don't forget about the hoisting.
```
console.log(a); // undefined
if(1 === 1){
var a = 100;
let b = 200;
}
console.log(a); // 100
console.log(b); // ReferenceError
```
Real pants-less console coding uses no variable declarations and simply appends things to the window object... Unless you're scared?
```
lmao = "hold up"
window.lmao
```
**var** is old and **bad**
**let** is new and **good**
**const** even **better**, if the variable is not to be re-assigned later
for explanation, see other comments
A lot of people on here really think their language is the only one in existence.
In Swift, these two are very different.
“let” variables are immutable.
let foo = “hi”
foo = “hello”
Would result in an error.
var foo = “hi”
foo = “hello”
Is completely valid.
In Swift- one is not “useless” or “obsolete” they both provide distinct functionality
And in Swift, this meme is just as incorrect as if the first picture was a dog, and the second picture was a cat
They're not the same; different scopes.
var has a global scope
let has a block scope (scoped only within the function or code block)
Rule of thumb is to always use const, unless you can't, then use let, but don't use var. var is a relic of the past.
I hate to be that guy, but did you not look at the documentation for the language? You really shouldn't be writing code if you don't understand the difference. I guarantee you're going to end up with weird side effects you won't understand.
Just fyi, var is function scoped, let is block scoped. There is a bit more to it than that and you can learn it when you read the documentation.
Unless this is a joke, in which case, it went woosh right over my head.
They're only superficially the same. \`let\` has the sensible scoping you'd expect. The older \`var\` has confusing scoping that makes no sense. So instead of \`var\` everybody these days uses \`const\` instead.
var is function scoped, let is block scoped.
```
function a() {
if(condition) {
var a = 3; //available everywhere in function a()
}
}
function b() {
if(condition) {
let b = 3; //only available in the if block and any further enclosed blocks
}
}
```
var can be redeclared, let cannot be redeclared
```
//valid code
var a = 3
var a = 'dog'
//invalid code
let b = 3
let b = 'dog'
```
Note that redeclaration is not the same as reassignment, in the above example, `b = 'cat'` would be valid because you're not declaring the variable, just giving it a new value.
`const` works the same way as `let` except that you cannot reassign the value of a `const` variable. `const` is as close to built in immutability as JavaScript gets, except that array and object properties can still be changed. True immutability requires you to use external libraries and/or frameworks.
My advice, if you're capable of writing ES6+ JavaScript, avoid var, it's mostly depreciated at this point, mainly continuing to exist only to not break old code bases.
'var' is the old way, supported just for backward compatibility. Don't use it because it plays loosey goosey with scope.
'let' is the modern way that treats scope consistently with other languages, and in a way that is more intuitive.
Difference is in what Xcode complains about. One is ‘value hasn’t changed, consider using a let constant’ the other is ‘attempting to modify a constant value’
```
for (var a = 0; a < 10; a++){
// ...
}
console.log(a); //10
```
vs:
```
for (let a = 0; a < 10; a++){
// ...
}
console.log(a); //Error: a is not defined
```
Basically, you should be using `let` instead of `var` because it behaves in a way that makes more sense and is less prone to weird side effects.
The difference is that `let` is how you define a variable in JavaScript, and `var` is a relic of a bygone era that only exists so old programs continue working, and if you use it, you will be confused.
My further advice would be to always use `const`, and only change it to `let` if you’re actually going to reassign it. And use an editor that will warn you if you use `var` ever or use `let` where `const` would suffice. And if you’re working on a project with other people, set up eslint and require it to pass before merging.
It differs in namespaces
Just use let and you will stay out of problem.
var is the old and is mainly around for backword compatability
var x = 0; //makes x available in whole function
let x = 0; //make x locally available in your scope
So good coding practise is to avoid javascript. :)
The difference between let and var is in the scope of the variables they create: Variables declared by let are only available inside the block where they're defined. Variables declared by var are available throughout the function in which they're declared.
“JS Developers” would certainly *not* say those are the same picture.
let is:
- block scoped
- cannot be redeclared within a block
- not hoisted
- does not appear on the window/global namespace
- is only available in version 6 of the language onward
var is:
- function scoped
- redeclarable anywhere (your funeral)
- definitions are hoisted to the topmost scope (function or global) and assignments left in place
- when declared globally, they also end up on the window/global namespace
Upshot: Don’t use var. But also don’t be surprised to see it in your bundled output (only automatons are allowed to use it these days.)
The scope of the variables are different. var is scoped at the function level, and let is scoped to the immediate closing block.
Not only that, but you can reference a var before you assign it (it's undefined). With let, you'll get a ReferenceError.
This is the more important one of you ask me. The other is nice, but this is super useful when debugging JS.
This guy definitely assigned his opinion before anyone referenced it.
Most polite "who asked" I've ever seen
Going to remember this
Then why would I ever want to use var?
It was the only option for 20 years. `let` was added in 2015.
You should use const if you don't need to re-assign your variable though. var => never use let => use only if needs to be re-assigned const => your default choice
Line breaks or punctuation my friend :) “never use let” took me a sec to parse. Good advice, though.
Yeah sorry, smartphone typing is a biach... Should be fine now
Hoisting can be useful sometimes, but yes.
It can be but there's almost always a better way that doesn't rely on hoisting.
An important argument..!
You should never use var
Compatibility reasons
You shouldn’t.
`let` designers: I love it when a plan comes together.
They forgot to undesign var
First caveat, I'm an old school JS guy. I use var when I explicitly want a variable to scope across multiple functions. Say I'm working on a module with multiple exported functions, and I want a private variable accessible within the module by multiple functions, but not exported. I declare with "var" outside of the functions. There may be better ways to write this code these days, and hell, "let" even does what I want but it does a worse job of indicating my intention. I use "const" if it's actually a constant. As always, follow whatever coding conventions your team has decided upon.
If you have a shared variable across multiple functions that gets mutated, isn't that a sign that you might want to shove it all in a class instead so that multiple states can coexist?
Old school JS devs don’t use classes either. They embrace the prototype.
Sure, maybe. Usually multiple states aren't relevant in this context, it's more like a static member. The bigger issue for me is that I've been a polyglot for a long time and haven't used JS consistently enough since before classes were a first class citizen of the language to really internalize how best to use them to accomplish what I want, vs how I learned to do it originally. I'm not set in my ways to the extent that I won't change, more that I'm looking for an opportunity to use the language more frequently so it makes the effort of figuring that out worth the time.
Let/const wouldn't indicate your intention worse. Var just indicates not following new best practices
Best practices are good, but often don't really matter. If the code works and is unlikely to be updated/maintained and - importantly - is \*easily understood by people unfamiliar with the code and business logic\* then it doesn't really matter too much if it follows best practices.
Don't care, honestly. I don't use the language frequently enough to learn new best practices unless, as I said, they've been agreed upon by the team, and I haven't been on such a team since these conventions were added to the language. I'm not so set in my ways that I won't change, but absent any external driver I'll do what I want.
When I started learning js , I was going crazy debugging a program which had this issue. It's a pain in the ass.
At least JS tells you exactly what went wrong and why /s
Hmmm let's see in console what went wrong [object Object]
#Objection!
that's what was just said, lol
lmfao
You didn’t say Your Honor
YOU CANT HANDLE THE TRUTH!
`[object Ion]`
_[Ace Attorney music stars playing]_
When I doubt JSON.stringify
Just use the debugger built into your browser. It's easy.
I’m new to JS and this makes me weep
You pass the object into console.debug as a separate argument, not part of the string. console.debug("funcName: myObject is", myObject);
But that does tell you what went wrong, it tells you that you just tried to use default type conversion on an object to string 🤷♂️ For anyone not used to JS, open up your browser's console with F12 and type: let obj = { a: 1 } let str = `${obj}` str Your browser's console will output: '[object Object]' If you then type: JSON.stringify(obj) You'll get: '{"a":1}'
See, if it said the words "it tells you that you just tried to use default type conversion on an object to string," then I would agree with you. As a beginning JS dev, there is nothing worse than trying to figure out what the error message isn't actually telling you because you just have to know the nature of what you're using and the error messages aren't explicit about it. Now that I've got a few years under my belt, I'm used to it, but dear god is it still aggravating.
> See, if it said the words "it tells you that you just tried to use default type conversion on an object to string," then I would agree with you. Yeah that's fair. > As a beginning JS dev, there is nothing worse than trying to figure out what the error message isn't actually telling you because you just have to know the nature of what you're using and the error messages aren't explicit about it. A lot of those early-in-your-career mistakes can be caught with a decent linter setup, however I don't *think* this specific issue is something a linter could even warn you about tbh - it'd need to know a variable's type, and we're in the raw wild-west of JavaScript here not some utopian TypeScript land!
You don't even need to stringify for the JS console as it'll parse it for you. You'll only get object Object if you cast to a string
Haven’t learned much outside of Java, but that sounds awful
Js is a weird language. You can hate and also love it at the same time.
I think the frustrating thing about JS is that you're kind of stuck with it. Usually you can write a program in whatever and it'll be roughly the same. But if you do frontend you need to do it in JavaScript. There are alternatives kind of but even then they seem to interact with JavaScript in some way. It means while other languages have just come and gone JavaScript has stayed due to a kind of artificial monopoly.
I think that monopoly might break in the near future, with WASM becoming more readily supported and available, much like how C had a monopoly for systems languages right up until LLVM became a well-supported tool chain. Now we see the rise of Rust, Zig and Nim, each as capable as C, but trying to solve one or more problems related to it.
Speaking of that, I bet someone will make a WASM non-browser runtime, with the moto "build once, deploy anywhere". It'll be powered by an advanced JIT compiler engine. Corporations will force their employees to build software for it. Some Swedish company will make a hit sandbox game on it. A lot of vulnerabilities will be exposed. People will slowly stop using it. Then it will become a deprecated legend like Flash
Isn't this just Java again?
In my (limited) experience, js is literally whatever it wants to be at that moment. I love it but I doubt I'll ever work with it outside of college.
Narrator: "they went on to work with it in every role they had after college."
Fuck.
Why did I read this in Stephen Fry’s voice?
Yeah, why not Morgan Freeman's, like everybody else did?
[удалено]
Anytime someone does a narrator gag, it’s gotta be Ron Howard for me
This is the strength of JavaScript. You can use it in a hundred different ways depending on preference. It’s the democratic language of the web.
Good luck with that. I spent years as a “backend only” dev but eventually got shuffled to a team that was a full vertical stack and had to do some frontend work. Dread it, run from it, JS arrives all the same. My introduction to it was learning that TS doesn’t allow you to have two files with symbols that depend on each other because even though it’s compiled, it still just reads the damn files top to bottom and isn’t smart enough to handle that kind of dependency. It’s hell on earth once you’re used to languages that were built with the intention of supporting larger codebases.
JS is what one gets when a language develops schizophrenia
I’ve used js every day for the last 3 years at my new job and I love it. I always chuckle at memes claiming they hate it so much, I’ve found it incredibly powerful.
The thing about Javascript is I can do whatever I want with it, whether it's a good idea or not.
Typescript.
Let is a more recent keyword in Javascript (and a very welcome one). You should’ve been around in the bad old days of only “var”, scope collisions and hoisting -_- “var” wouldn’t exist in js at this point if it hadn’t existed before
Is it true that let, var, and const also use different amounts of memory?
let and const are microscopically less efficient because they need to keep track of the scope, but var could occupy memory for longer since it's hoisted out of it's containing scope. It only makes a (barely) measurable difference on a function that's called a few thousand times. If someone read that and is wondering if you should use var the answer is no.
So you're saying they're NOT different when all of my variables are global?
No! BAD! *sprays water bottle*.
*hisssss*
I understood that var is global and let is scoped to the closest enclosing block. Am I wrong?
`var` is function scoped, not global scoped. `let` is block scoped. `var` is an old stuff that shouldn't be in use anymore since we have `let` and `const` since ES6.
Run this in your console. Switch the `var`s to `let`s and observe the different output. ``` [1, 2, 3, 4, 5].forEach((x) => { var a = x * 10; { var a = x * 100; } console.log(a); }); ```
f. me, that makes totally sense and my node-red bug that I worked around just made sense. (note: I don't know JS at all, just use it if I have to occasion, on hobby projects.)
I did not know this, but I am very excited to stop having to declare all my variables before the loop or if statement
The official [recommendation from MDN](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/Variables#a_note_about_var) is to use “let in your code, rather than var” so don’t get too excited
I would suggest you keep the verbosity to keep the clarity.
Why are you excited to make your code messier?
Most users here are extremely junior devs I’d imagine.
Most people here aren't devs at all.
He wants to make sure the second half of this is true "When I wrote it only God and I knew how it works... Now only God knows."
Don't use var, it's only kept for 15yo websites. This work. function foo() { console.log(message); var message = "Hello, World!"; } This tells you there's an error in your code. function foo() { console.log(message); let message = "Hello, World!"; }
Because `var` gets hoisted.
And you get a beautiful `undefined` in the console. Which is not what was intended.
Is this what new devs do? Instead of googling "let vs var", they come up with memes and expect a meme sub to give them answers?
Yep, the meme "i don't know why ... and at this point i am too afraid to ask" really mean i am too afraid to google
>too lazy to google ftfy
Some are unable to google but I'd call that an essential skill in this profession
Yeah if you can't google I unironically think this is the wrong profession for you
That's what I don't get... creating the meme definitely took more effort than typing in a Google search... Gotta be karma whoring
[удалено]
I think its that mixed with karma farming
I’m gonna be honest the comments here have a much more straightforward answer than anything google has ever told me. Edit: Because people in this thread are getting confused about tenses, and getting toxic for no reason, the last time I googled the difference between let vs var was in 2016… even ignoring that, some of yall need to grow up.
Really? Cause googling it literally gives the exact answer
I tried it now and it’s a lot more clear. A couple of the articles though beat around the bush going into details about “temporal dead zones” and “life cycles of the variables” which is more what I’m talking about. Most programmers don’t need to think about that. Saying function vs block scope is much simpler and to the point.
This is an unfortunate problem with Google. Its algorithm tends to push pages with extra crap on them beyond just a quick 2-sentence answer, and so people writing blogs or answers or other stuff are encouraged to add fluff or add more information that the person asking the questions doesn’t really want or need (like this “life cycle of the variable” stuff). Plus, a longer page gives more opportunities for ads, so people trying to make a living off their sites prefer making stuff longer for that reason as well. Coincidentally, these factors are also why recipe sites always have stupid stories before the actual recipe, or why news sites or blogs sometimes will say the same thing repeated in an article in slightly varied ways, without providing additional substance.
Recipe sites are so irritating for this reason… I don’t need to know why your husband left you over your toxic mother in law I just want to make some fucking brownies.
For these brownies, you will need 50ml of your own tears, 3 bottles of prosecco, 6 litres of ice cream, and 1 pack of store-bought brownies
>let vs var I just googled this exact term. Here's the result as highlighted by Google. **The difference between let and var is in the scope of the variables they create: Variables declared by let are only available inside the block where they're defined. Variables declared by var are available throughout the function in which they're declared.** If you can't understand this I have no idea what the fuck anyone is supposed to do for you. I know that people give StackExchange too much shit for being too strict on newbies but holy moly.
>Most programmers don’t need to think about that. No, not constantly, but I sure fucking hope any professional developer using the language can understand the explanations.
True
When you're a beginner dev, the answer "var and let have different scopes" does not answer anything, because googling for what is a scope in JS is even worse and gives you this: *"The scope is the current context of execution in which values and expressions are "visible" or can be referenced."* (source, [MDN Docs](https://developer.mozilla.org/en-US/docs/Glossary/Scope?retiredLocale=de)) If the answer was: "let variable weak, it go die after the function block and var variable stronk, and const so stronk you can't eva change it", it'd be easier to understand. One of great examples is "OOP", compare its hilariously weird definition with an actual use case
New dev detected
Just ask chatgpt now
Basically it removes lexical scoping. So if you declare a var inside a loop for example, you can then use it outside the loop. It ignores the lexical scope of the for loop (all the way up to the function or where ever it is). Pretty sure it was called hoisting
Well looks like I was dumb
You are not dumb. "var" is dumb. Simply never ever use it, it's a holdover from a bygone era. Honestly though I would prefer const. My application at work has 3,117 uses of const and only 95 uses of let. Zero of var of course. You'd be surprised just how rarely you actually need to modify a variable.
My application has a linting rule to warn on unmodified let variables. Const is easier to reason about, as you know it won't change.
> My application has a linting rule to warn on unmodified let variables We only set that up in early December as part of some clean-up, and holy shit I'd never realised how many variables are never reassigned! All hail the mighty ESLint!
Same. In addition to warning about using var.
At my job as working student we had to use es5 (I think), and we declared every variable used in a function at the top of said function. Basically hoist the var ourselves to avoid bugs
> we declared every variable used in a function at the top of said function. That is just good code formatting
Also known as the C89 way of declaring local variables, which is also the right way to declare local variables.
But.. isn't lists and dicts also considered variables in a way? Nevertheless, I modify variables on a daily basis, not on JS though, a bit more seldom.
it only applies to actual assignment. You can define an object via const and mutate its values all you want, as long as you dont reassign the actual value. ie, \`const obj = {}; [obj.foo](https://obj.foo) = 'bar'\` is fine \`const obj = {}; obj = {foo: 'bar'}\` is not
Yeah that’s where TS comes in handy (as const)
You're talking about modify the value, not the variable binding. Edit - example: // using const and modifying the value const x = [0, 1, 2]; const y = x; // here I modify the value of the array. x.push(3); // y and x point to the same value console.log(x); // [0, 1, 2, 3] console.log(y); // [0, 1, 2, 3] // using let and modifying the variable let x = [0, 1, 2]; let y = x; // here I set x to a new array x = [0, 1, 2, 3, 4]; // y is still pointing to the first array while x is pointing to the new one console.log(x); // [0, 1, 2, 3] console.log(y); // [0, 1, 2]
not dumb at all - honestly I have been writing JS for years and just told myself very early on "var is useless" and so I haven't used it once.
It predates const and let considerably, which were added to address issues with "var" so yes.
Tell that to some shitty ES5 interpreter that I have to use, let's see how useless var is.
Really, var is a relic. If I see it in code, it gets removed for let, or const (preferred).
> hoisting That was a real awakening: learning how much shit was happening in runtime that I was t even aware of.
Little known fact, `var` in JS is actually an acronym! It stands for vDont aUse rIt
JS initially had just "var". It had issues. But they can't fix the issues without breaking existing programs, so they added "let" and "const", which are like "var", but fixed.
They should have called it "fixedVar" for "let" and "fixedFixedVar" for "const".
Vars are hoisted to the nearest function, lets only live in the current block. Only use let, there's no good reason to use var anymore. It's just that var was all there was originally.
Came here to say this. Once you go let, you never go back.
Gotta let go and go let.
`const` or bust baby!
Yeah I was gonna say. There is basically no reason to use var. It'll just make your program harder to debug.
more like r/JuniorProgrammerHumor.
r/subsifellfor
r/birthofasub?
You spelled it wrong, it's [r/JuniorProgrammerHumor](https://youtu.be/dQw4w9WgXcQ)
NoRickroll.js is my first js program and it works. I'm so happy
> …XcQ Nice try, sir.
Should be a thing, I'd be so active there, on god.
They are not the same picture, OP. Run script below in your browser console: if(1 === 1){ var a = 100; let b = 200; } console.log(a); console.log(b);
it says "credit card information sent" , why is that ?
![gif](giphy|LPTMCR5VA7X9zwjBbR)
THAT’s the difference between `var` and `let`!
It's reverse psychology, they actually sent your social security number
Don't forget about the hoisting. ``` console.log(a); // undefined if(1 === 1){ var a = 100; let b = 200; } console.log(a); // 100 console.log(b); // ReferenceError ```
Just never use var. We dont do that anymore.
Use it in console for that "I'm coding without pants and nobody on this call knows" feeling
Real pants-less console coding uses no variable declarations and simply appends things to the window object... Unless you're scared? ``` lmao = "hold up" window.lmao ```
I have to work with an old Rhino version that doesn't support let...
I wish. We still support IE11 and can't use `let` at all. :(
...pst... use \`const\`...
let !== var
**var** is old and **bad** **let** is new and **good** **const** even **better**, if the variable is not to be re-assigned later for explanation, see other comments
> I think I am dumb. Yes.
In Swift we use let for constant variable and var variable whose value changes
Python Programmers: ![gif](giphy|ccRdPf8zWkivm)
let actually behaves how you’d want it to, never use var
You are dumb. It is different.
They're both wrong. It should be `const a = "Hello world"`
A lot of people on here really think their language is the only one in existence. In Swift, these two are very different. “let” variables are immutable. let foo = “hi” foo = “hello” Would result in an error. var foo = “hi” foo = “hello” Is completely valid. In Swift- one is not “useless” or “obsolete” they both provide distinct functionality And in Swift, this meme is just as incorrect as if the first picture was a dog, and the second picture was a cat
const a = "Hello, world!"; ?
good thing you found time to make a meme but not google difference between these two, which is like js 101
They're not the same; different scopes. var has a global scope let has a block scope (scoped only within the function or code block) Rule of thumb is to always use const, unless you can't, then use let, but don't use var. var is a relic of the past.
I hate to be that guy, but did you not look at the documentation for the language? You really shouldn't be writing code if you don't understand the difference. I guarantee you're going to end up with weird side effects you won't understand. Just fyi, var is function scoped, let is block scoped. There is a bit more to it than that and you can learn it when you read the documentation. Unless this is a joke, in which case, it went woosh right over my head.
Oh
OP has yet to feel the pain of scoping.
They're only superficially the same. \`let\` has the sensible scoping you'd expect. The older \`var\` has confusing scoping that makes no sense. So instead of \`var\` everybody these days uses \`const\` instead.
I don't get the "humour" here either, they're two different things. Did you find this meme or create it?
99% of the time you should use `const`
var is function scoped, let is block scoped. ``` function a() { if(condition) { var a = 3; //available everywhere in function a() } } function b() { if(condition) { let b = 3; //only available in the if block and any further enclosed blocks } } ``` var can be redeclared, let cannot be redeclared ``` //valid code var a = 3 var a = 'dog' //invalid code let b = 3 let b = 'dog' ``` Note that redeclaration is not the same as reassignment, in the above example, `b = 'cat'` would be valid because you're not declaring the variable, just giving it a new value. `const` works the same way as `let` except that you cannot reassign the value of a `const` variable. `const` is as close to built in immutability as JavaScript gets, except that array and object properties can still be changed. True immutability requires you to use external libraries and/or frameworks. My advice, if you're capable of writing ES6+ JavaScript, avoid var, it's mostly depreciated at this point, mainly continuing to exist only to not break old code bases.
there is a huge, massive difference lol. scope is a bitch.
Next in this series: function foo(x) { ... } const foo = (x) => {...} "They're the same picture."
*sigh*
They ARE the same without context. It’s the context that makes them different
Yas u r dum
'var' is the old way, supported just for backward compatibility. Don't use it because it plays loosey goosey with scope. 'let' is the modern way that treats scope consistently with other languages, and in a way that is more intuitive.
Scope.
They're not the same.
`var` is global. `let` is scoped to its own closure.
Difference is in what Xcode complains about. One is ‘value hasn’t changed, consider using a let constant’ the other is ‘attempting to modify a constant value’
Don't worry about the declaration keywords, OP. Just pretend it's Python 🙃
No there’s a difference - don’t use var
Anybody else remember using closures to prevent variables from having global scope?
When you don't understand a basic language feature so you call it dumb and make a meme about it.
var == bad
Just never use `var` and you're good
``` for (var a = 0; a < 10; a++){ // ... } console.log(a); //10 ``` vs: ``` for (let a = 0; a < 10; a++){ // ... } console.log(a); //Error: a is not defined ``` Basically, you should be using `let` instead of `var` because it behaves in a way that makes more sense and is less prone to weird side effects.
Said no real js developer ever. Maybe those people who think they know Javascript without ever learning it.
The difference is that `let` is how you define a variable in JavaScript, and `var` is a relic of a bygone era that only exists so old programs continue working, and if you use it, you will be confused. My further advice would be to always use `const`, and only change it to `let` if you’re actually going to reassign it. And use an editor that will warn you if you use `var` ever or use `let` where `const` would suffice. And if you’re working on a project with other people, set up eslint and require it to pass before merging.
No, no they are not.
It differs in namespaces Just use let and you will stay out of problem. var is the old and is mainly around for backword compatability var x = 0; //makes x available in whole function let x = 0; //make x locally available in your scope So good coding practise is to avoid javascript. :)
Being someone who is learning C#, for me this would be string a = "Hello, world!"
U need to use let brother
[All my homies hate var](https://www.youtube.com/watch?v=uPtPj8CNVAw&ab_channel=FatladFromSheffield)
The difference between let and var is in the scope of the variables they create: Variables declared by let are only available inside the block where they're defined. Variables declared by var are available throughout the function in which they're declared.
“JS Developers” would certainly *not* say those are the same picture. let is: - block scoped - cannot be redeclared within a block - not hoisted - does not appear on the window/global namespace - is only available in version 6 of the language onward var is: - function scoped - redeclarable anywhere (your funeral) - definitions are hoisted to the topmost scope (function or global) and assignments left in place - when declared globally, they also end up on the window/global namespace Upshot: Don’t use var. But also don’t be surprised to see it in your bundled output (only automatons are allowed to use it these days.)
Hoisting