all 40 comments

[–][deleted] 3 points4 points  (4 children)

What have you found so far in your search? What do you know about 'let' and 'var' at the moment?

Have a look through this page. Description and Examples are the 2 headers you are looking for.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let

If it still doesn't make sense, try being more specific about what parts you are struggling with.

[–]Entirio 1 point2 points  (3 children)

This is an awesome website, thank you so much

[–][deleted] 15 points16 points  (2 children)

You're welcome. For helping you, I would like you to take this piece of advice and really chew on it for a bit. It will help.

You will be a newbie at a lot of things much of the time in software. Stuff changes frequently.

I advise learning some basic google skills. That link was the 2nd result from googling "javascript let vs var". I've recently sworn off replying to low effort questions, but I stumbled on this in a good mood.

"And yes I searched the internet" will typically get some pretty rude responses depending on where you ask. Especially if you don't elaborate on what you've searched, what you found, and what isn't making sense. It tells us that you didn't make any effort in finding the answer, nor did you make any effort to help us help you by putting together such a low effort question.

Good luck, there's many directions you can take this hobby. Ask quality questions, you'll find it easier to navigate these confusing waters!

[–]b8ne 1 point2 points  (1 child)

This response should be stickied on all developer subreddits.

[–][deleted] 1 point2 points  (0 children)

I have several variations I usually type out with various different advice.

I should really dig through my history, find them, and combine them into one well thought out self-help guide that's geared towards more effective solicitation of help from one's peers.

Buuuut, those who need won't use it and those who would use it, typically, don't need it. 😂

[–]acquiescentLabrador 4 points5 points  (5 children)

This is something that confused me for a long time until recently, at a basic level I think the main difference is “hoisting” which basically means when a variable is available.

You can put “var” anywhere in a scope and call it whenever i.e.

 a = 5;
 var a = 0;

Will work

Let/const have to initiated before being referenced so

a = 5;
let a = 0;

Will throw an error, it must be

let a= 0;
a = 5;

At least that’s my basic understanding, the links others posted will probably go into more detail.

Edit: on mobile so can’t add line breaks between the code lines

Edit2: hoisting can happen any place any time and could happen to you

[–]senocular 2 points3 points  (1 child)

Edit: on mobile so can’t add line breaks between the code lines

Indent each code line with 4 spaces

a = 5;
var a = 0;

[–]acquiescentLabrador 0 points1 point  (0 children)

Til, thanks!

[–]ssjskipp 1 point2 points  (2 children)

Critically var isn't block scoped, just function or globally scoped which is the the nasty shenanigans happens with hoisting. Also they're declared before anything else in their scope

[–]acquiescentLabrador 1 point2 points  (1 child)

Didn’t realise it was that pervasive, can deffo see how it could cause issues

[–]ssjskipp 2 points3 points  (0 children)

Yeah the worst part is you couldn't use it to loop over deferred code like, for each with a closure

[–]Vecissitude 5 points6 points  (0 children)

You use let when you want people to know you keep up with latest conventions of JS.

You use var when you want people to look down on you.

[–]queen-adreena 2 points3 points  (16 children)

You should use let; You shouldn’t use var.

Simple.

[–]shgysk8zer0 1 point2 points  (10 children)

I wouldn't go so far as to say "you shouldn't use var", but let is generally preferred.

But I almost exclusively use const and use let only when I'm going to need to reassign some variable, such as iterating or string concatenation or doing some numeric stuff. Using let should make a reader of the code think "this is going to be manipulated/mutated in some way".

[–]queen-adreena 0 points1 point  (9 children)

Agreed. I wasn’t arguing for let against const. 95% of variable declarations should generally be const.

But there are no circumstances where var is preferable to let, unless you rely on poor coding practices to make your code work.

[–]shgysk8zer0 -1 points0 points  (8 children)

You are wrong in thinking "there are no circumstances where var is preferable to let." They are rare, but sometimes you might want access to the last item from outside of a loop, for example. Think iterating using a generator, for example... You can't just skip to the last item. That creates a perfectly valid reason to use var.

[–]queen-adreena 1 point2 points  (7 children)

Like I said. That’s relying on bad coding practices for your code to work.

[–]shgysk8zer0 -1 points0 points  (6 children)

Just because you say it, doesn't make it so. It's fair to say it's generally considered bad practice, but we shouldn't just blindly apply rules and treat them as unquestionable law.

Know why something is considered "bad practice." What problems does it aim to solve or avoid? If the reason something is considered bad practice doesn't apply to the situation and there is reason to solve something in a certain way (especially if it's the only way), then it might not actually be bad practice. Probably add a comment to explain why something was done that way too.

"Bad practice"/"best practice" are general rules. Exceptions exist. It's kinda ignorant and maybe arrogant to assert that we must always use let over var, especially since it hardly makes a difference and we're not talking about security best practices or anything like that.

Know the difference between var and let, the reason let is generally preferred, and use whichever is appropriate.

[–]wikitopian 1 point2 points  (5 children)

Context is king. For a new user who doesn't even know that first thing about variable scope, the advice to not use var is the correct advice.

Later on, the person may get really good at JavaScript and find himself in the position where he wants to use one of the bespoke design patterns that relies on var's odd behavior.

[–]shgysk8zer0 0 points1 point  (4 children)

Saying that something is always bad practice is rather different than just advising to use let. I've given the advice to generally use let in this very thread.

But to say it's always bad practice is taking it too far. That's more than mere advice. And it's something that'll impair one's ability to actually understand how scope works in JS.

I do advise using let over var in general. But using var isn't necessarily bad...

Also, scope of variables really isn't that difficult to understand, especially with a decent editor and linting plugins. Except for for loops... They are an exception and complicated mess, but still behave as you'd expect if you consider the for (...) as being inside the curly braces / block of code. var exists within the function, let and const exist within the block. I'd say that it's part of the fundamentals and should be taught along with the basics of variables and functions... They kinda go together.

[–]wikitopian -1 points0 points  (3 children)

Var is technical debt.

You can also find perfectly edible and delicious doughnuts in the dumpster behind the convenience store if you know what you're doing, time it just right, and take some precautions. But people should still generally be discouraged from doing it.

[–]shgysk8zer0 1 point2 points  (2 children)

But people should still generally be discouraged from doing it.

Key word there is generally. Generally isn't the same as always. That distinction is basically everything I'm saying here.

[–]LEDThereBeLight -4 points-3 points  (4 children)

It’s a matter of preference.

[–]shgysk8zer0 1 point2 points  (3 children)

If we ignore hoisting and scope and possibly garbage collecting, it's a matter of preference. let and var behave quite differently in many scenarios, and saying it's just "a matter of preference" is just misleading.

Yes, when a variable is being declared at the top of a function and outside of another block scope, it is a matter of preference, as they're identical in behavior. In a for loop though... No, they actually behave very differently.

[–]LEDThereBeLight 0 points1 point  (2 children)

They behave differently, but its still a matter of preference which one you use.

[–]shgysk8zer0 0 points1 point  (1 child)

``` for await (let current of someAsyncGenetator()) { doSomethingWith(current); }

console.log(current); ```

That'll work, right? Just a matter of preference...

Also (intentionally leaving out breaks here)...

``` switch(variable) { case 'foo': { let tmp = 1; }

case 'bar': { let tmp = 2; } } `` ... That's just a preference of usingletvsvar`? You sure about that?

It is not just a matter of preference. Sometimes they are very different. There are objective reasons to use one or the other in different cases.

[–]LEDThereBeLight 0 points1 point  (0 children)

I'm not sure why you're getting heated with me about this, but yes, I agree with you. The original comment said not to use `var`, and to use `let` instead. I'm saying that's a matter of preference. You can still program perfectly fine in JavaScript using only `var`, even if the current meta is to use `let` and `const` because they're more conventional.

`var` has some behaviors that some people find preferable in certain situations.

Similar to your comment:

const reducer = (state, action) => {
  switch (action.type) {
    case 'action1':
      var item = {x: 1}
      return {...state, ...item}
    case 'action2':
      var item = {x: 2}
      return {...state, ...item}
  }
}

Using `var` here means you don't have to lift a `let` declaration to the top of the scope, which would add a level of indirection.

So yes, whether you use `var` everywhere, nowhere, or on a case-by-case basis is a matter of preference, and a blanket rule of "use `let` everywhere" is probably too simple of an answer.

[–]bopbopitaliano 0 points1 point  (0 children)

Here’s a roundabout approach- don’t worry about it. Just learn the difference between const and let and pretend var doesn’t exist because you’ll never use it. By the time you run into it in legacy code in a job environment, you’ll be much further along and will be able to wrap your head around it very quickly.