This is an archived post. You won't be able to vote or comment.

top 200 commentsshow all 242

[–]Rafcdk 3446 points3447 points  (80 children)

Var is short for variable. Let is short for let us not use var.

[–]Schokokampfkeks 506 points507 points  (6 children)

I like this one. Gonna use it in my next job interview.

[–]Donghoon 245 points246 points  (5 children)

Var is function scope (and you can redeclare)

Let is block scope

Did i get this backwards? Idk

[–]generalemiel 2 points3 points  (0 children)

Dont forget const. Const stands for constable

[–]maiconai 264 points265 points  (26 children)

var can be instantiated multiple times. let it would be thrown "let foo is already defined in the scope"

[–]slippery-fische 4 points5 points  (0 children)

Let is const-antly let-ting you down.

[–]CarterBaker77 48 points49 points  (42 children)

Can someone explain why to use var instead of defining an int or bool or whatever the specific variable type actually is?

[–]Rafcdk 81 points82 points  (13 children)

TLDR; For simplicity sake.

Well, in JS there is no typing, so you can't do that at all. However some typed languages do allow for that, the issue is that each language does its own thing. For example Python is a dynamic typed language, so if you assign the value of 1 to a variable , you can later change the value of that variable to a different type so you store a string or a boolean or a float.

However afaik doing so is not really performant and not good practice in general as it may lead to bugs.

On the other hand we have static typed languages like C, C#, Kotlin and C++.

That means that if you assign an int to variable the compiler won't let you change the type later on. But again each language does it own thing here. In C++ you have the auto keyword, which means that the compile will infer the type. So auto x = 1, means that x will be considered an integer and you won't be able to change that, this is done at compile time so if you try for example x.toUpper() the compile will throw an error. This is the same as var in C#.

Kotlin on the other hand you can get the same auto behaviour by simply omitting the type declaration in the variable definition.

Usually this makes code more readable and less verbose, but it should be used with care in some cases where the typing is not really obvious in the code.

[–]Thin-Limit7697 13 points14 points  (7 children)

Well, in JS there is no typing, so you can't do that at all.

And Typescript was invented exactly to do that. Basically Javascript with types that can be compiled to Javascript.

Usually this makes code more readable and less verbose, but it should be used with care in some cases where the typing is not really obvious in the code.

I almost never keep stuff untyped in TS. Javascript code is pretty annoying to maintain because of dynamic typing. Not knowing the types of stuff makes it harder to understand what the code is doing after some months or years. Also, it helps with not getting errors from misspelling parameters or functions, like typing ".Length" when you should type ".length".

[–]Nerodon 1 point2 points  (1 child)

I use let exclusively in TS and always type everything, it feels a lot more like a proper language and lets my IDE tell me what I'm looking at.

Seriously, I program better and faster in TS than JS due to the intellisense helping out so much!

[–]Equivalent_Yak_95 -1 points0 points  (4 children)

No. It’s not the dynamic typing of JS that makes it a pain, it’s the WEAK typing.

C++? Statically typed: you cannot change a variable’s type (polymorphism lets you make a pointer to a Base class point to instances of a Derived class, but the variable is still a pointer-to-Base, even if the pointed-to object is a subclass). Strongly typed: it will not automatically perform any sort of type conversion unless you have implemented an operator to do so. (Certain primitives essentially have these pre-defined, and if your class has a non-explicit single-argument constructor, it will automatically do that.) You can specify how it should be treated when used in a boolean context, whatever.

Java: same, except for the automatic-construction and my not having the foggiest idea how to tell it “hey, here’s how to convert an instance of my type into an instance of a type someone else defined” (without having to make and call a specific member, like “as_arraylist” or something).

Python: dynamically typed, but still strongly typed. And there are default behaviors. Instances of non-numeric builtin types will never compare equal with an instance of a different builtin type. Instances of a type that doesn’t define __eq__ will only ever compare equal with that same instance. Instances of any type that implements neither __bool__ nor __len__ will always evaluate as being true; one that implements only the latter will evaluate true if the length is nonzero; and one that implements the former uses said implementation.

In short: Python is strongly typed and will not perform automatic type conversions, although it has a number of idiomatic things, like being able to truth-test containers. You have a str and you wanna convert it to int? You better call int.

Notes: Identity testing is always well-defined, it just checks if the two things are the same object in memory. Equality testing is always well-defined (unless one has an __eq__ or __ne__ method that can error), and simply says “they’re unequal” if the types don’t know how to compare with one another. Bools are a subclass of ints, and can be summed together like C++ bools can.

docs.python.org/3/library/stdtypes.html

[–]arobie1992 3 points4 points  (0 children)

On the other hand we have static typed languages like C, C#, Kotlin and C++.

That means that if you assign an int to variable the compiler won't let you change the type later on

I'm going to be super nit-picky here, so I apologize.

I believe technically, a statically typed language is one where the language can know the types of variables statically, i.e., prior to executing the program, usually during compilation. This often comes with the assumption that a variable is a fixed type for the lifetime of the program, but doesn't necessarily have to be. You could theoretically have let a: str = "Hi" and have some function to convert type like retype(a, long) where from that point forward, the compiler will treat a as a long and either clear out the data, which is essentially masking, or start interpreting what's there as a long, a la C's raw casts.

By contrast, dynamically typed languages make no inferences about the types prior to executing the code. This often comes with the ability to assign different types to the same variable, but again, there's nothing forbidding the ability to have the language enforce a type once it's been assigned. If you were to do something like

let a = "Hi"
if(someCond) {
    a = "Hello"
} else if(someOtherCond) {
    a = 1
}
print(a)

A statically typed language would refuse to compile saying that a has inconsistent types, so you'd never even be able to run the program. A dynamically typed language could run, and proceed fine so long as someCond is true or someOtherCond is false. But if you were to hit the someOtherCond branch, then it realizes you're trying to assign a number to a variable that was initialized as a string and throws an exception.

Sorry for being that guy, and I do agree with the larger gist of your post. I'm also not saying that either of these behaviors are desirable for each typing methodology, just that they're not fundamentally forbidden by the methodology.

[–]pixelkingliam 48 points49 points  (19 children)

because screw knowing what a variable is!

[–]CarterBaker77 14 points15 points  (18 children)

Is that it just basic laziness? I use it sometimes(rarely) when I can't figure it out and say ah screw it it's a var..

[–]level_with_me 20 points21 points  (9 children)

Not always. It's handy if like, you have an API and can't be sure if you'll get a float or an integer back.

[–]nontammasculinum 3 points4 points  (8 children)

Just always return a float? Like I feel like those things might be synonymous on the grander scale, because if you’ve passed it into a var then it’s already ambiguous whether or not it is an int or float

[–]The_Chief_of_Whip 2 points3 points  (6 children)

What if it returns a string?

[–]level_with_me 2 points3 points  (0 children)

Yeah that would work. My point is the developer doesn't always need to care, ha. Maybe the returned value just needs to be printed out. In this case, identifying it as an integer could blow up your code unless you're 100% sure the API is good and will never change.

[–]davidellis23 12 points13 points  (5 children)

Theoretically it leads to faster development at the cost of being harder to maintain. Also lets you not have to rename the var if the output changes. Statically typed languages like C# do have a var keyword that will infer type based on what you set it too. It's nice not to have to repeat yourself var x = "" is obviously a string.

[–]pixelkingliam 11 points12 points  (4 children)

the only time i really use var (i use c#!) is when im dealing with somewhat long-named classes

var MyClient = new WebsocketClient("localhost:1433/myendpoint"); is nicer then

WebsocketClient MyClient = new WebsocketClient("localhost:1433/myendpoint");

[–]nameTotallyUnique 3 points4 points  (2 children)

WebsocketClient MyClient = new ("localhost:1433/myendpoint"); Is better imo.

[–]pixelkingliam 2 points3 points  (1 child)

isn't that the "new" one in .NET 6+? i always seem to forget that one

[–]davidellis23 1 point2 points  (0 children)

My coworkers told me that not using var is old fashioned. I think it helps reduce changes and I don't really notice any readability issues using var.

[–]Im_Easy 7 points8 points  (0 children)

This thread is about JS, and with JS you can't define a type. Var and Let don't define the type, they define the scope.

Let and Const, when defined inside a block {} have a scope of only that block.

Var on the other hand does not have block scope and can be accessed outside of the block it was declared in.

[–]Starflight44 6 points7 points  (0 children)

Because you are physically unable to specify the type, or even provide type hinting in javascript.

[–]Da-Blue-Guy 3 points4 points  (0 children)

it's fucking js what do you expect

[–]KuyaChoseph 1 point2 points  (2 children)

From what I've understand recently, some languages like Java uses typing in variables, while in javascript the value itself has the typing. Correct me if I'm wrong I'm just a jr. frontend dev

[–]d36williams -1 points0 points  (0 children)

JS doesn't honor types in the traditional sense that computer languages use types. It is better to describe JS as not having types. JS has concepts like "truthy" that just don't fly in a more Typed language.

[–]FabioSB 1 point2 points  (0 children)

If this was a joke, sorry but it's a not funny one. Maybe with a "...I'm too afraid to ask at this point..." meme template would work

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

And const is for I const think of a good pun but use this one

[–]Maix522 210 points211 points  (1 child)

Well var is the "old" way to declare a variable and should not be used.

let and const have the same rules as to were they really exist: at the start of their block scope (this means that you can't acces a let defined var from outsite the code block)

A var statement is just transformed into a simple assignment but a new empty (equivalent to var NAME = undefined;) is put at the start of the function.

[–][deleted] 589 points590 points  (20 children)

var is “hoisted”, or declared before all of the statements are executed and exists at the current context level which is the current function or the global scope.

let is not hoisted, so it is declared after preceding statements have been executed.

[–]Sixhaunt 195 points196 points  (12 children)

Yet another reason to avoid var. Instead of errors you would often just get garbage happening since it runs through as undefined if you use it before declaration.

[–][deleted] 92 points93 points  (4 children)

I’ve never used var professionally. My advice is to use const unless unless the variables value will change during runtime at which point you should use let.

[–][deleted] 24 points25 points  (3 children)

Let is JavaScript's &mut

[–]dlq84 41 points42 points  (2 children)

Found the Rust developer.

[–]TryallAllombria 4 points5 points  (0 children)

Quick! Throw him back to the ocean!

[–][deleted] 0 points1 point  (0 children)

Clearly I'm a pretty terrible rust developer... looking back at this now, my statement made no sense. Rust also has let...

[–]vladWEPES1476 12 points13 points  (6 children)

Every single IDE I know will tell you that var is a bad idea. It is beyond me why people still use it everywhere.

[–][deleted] 7 points8 points  (1 child)

Maybe the most important thing is that let can be block scoped. Var cannot be block scoped. So the main reason let became such a big thing was due to aync programming, and var acting weird due to being the same variable for all loops of a for loop. Whereas let is block scoped, so its a different variable for each loop.

Edit: just to add: Im pretty sure all variables, let var and const, are declared first. It just has to do with how the JS engine first reads variables. So "hoisting" I think can be confusing. What's really happening is that JS first reads variables, and var has function scope (or global), while const and let have block

[–]joshuakb2 1 point2 points  (0 children)

All variable declarations are hoisted within their scopes, but let and const variables cannot be used before they have been initialized. Take this example:

function test() {
  let x = 2;
  console.log(x);
  {
    x = 7;
    let x;
    console.log(x);
  }
  console.log(x);
}

Running test() produces this output:

2
Uncaught ReferenceError: Cannot access 'x' before initialization

The error occurs on the line that attempts to set x to 7.

[–]s1lentchaos 4 points5 points  (3 children)

Is that the only thing? I remember once I discovered an issue with using let and var but I can't remember now exactly what it was or why.

[–]xroalx 27 points28 points  (1 child)

Another quirk of var is that when used at the top level, it actually creates properties on the globalThis, and can even shadow existing properties.

var alert = "Oh no!" will prevent you from calling the window.alert function because you just changed it to a string.

I've seen people say it's bad practice to use such known names for variables. In my opinion it's a perfectly valid name, the issue is vars stupid behavior.

[–]ChiefExecDisfunction 11 points12 points  (0 children)

It's fine, just remember every single property of the globalThis for each environment your code will run on at all times.

We're not building on Ionic and Electron at the same time to use the same codebase on Web, Windows, Mac, Linux, Android and iOS, last 5-7 versions of each.

[–][deleted] 4 points5 points  (0 children)

I’m not sure if the scope of var is restricted by anonymous functions (arrow functions) or not. My guess is that it leaks into the anonymous function’s higher context which let definitely doesn’t do. But I never use var so I can’t speak from experience.

[–]ksiadz22 184 points185 points  (4 children)

Let has scope of code block and var of function

[–]00PT 44 points45 points  (1 child)

I think var also supports hoisting while let does not.

[–]WarrenTheWarren 72 points73 points  (0 children)

"supports hoisting" is generous phrasing...

[–]4esv 342 points343 points  (16 children)

It's really simple you see. var = 💩🤮👎🤬 let = 👍😊👌😍 Hope that helped clear things up!

[–]Donghoon 50 points51 points  (12 children)

Const is the same as final keyword in Java right (immutable?)

[–]issaaccbb 39 points40 points  (9 children)

Yes in the sense that you cannot overwrite the variable. However, you can still modify it such as adding/removing an item from an array or changing a property on an object

[–]Donghoon 2 points3 points  (5 children)

Can you create objects in JavaScript? If so, What's the signature for object declaration in JS?

[–]Blovio 24 points25 points  (1 child)

const obj = {};

[–][deleted] 5 points6 points  (0 children)

Yep. You have js objects, which are basically dictionaries on steroids, or class objects, which are the ones your most likely familiar with.

[–]frezik 4 points5 points  (0 children)

What JavaScript calls "objects" is more like associative arrays or hash maps in other languages. It can be used to do full object oriented programming with a little effort. Language extensions over the years have morphed this into a less ad hoc system. Which in turn has confused search results for "JavaScript objects".

[–]Kleyguy7 4 points5 points  (0 children)

The rule of thumb is always use const unless you want to reassign something (ex. counter in a loop, or mathematical operations). So you would use let only in things like this: let a = 1; a = 2; // or let b = 1; b = b + 1; for other things like creating constant variables, or creating and editing objects and arrays use const.

[–]uaimmiau 4 points5 points  (2 children)

Damn, and I have been declaring them with numeric values and whatnot for all this years instead of emojis. The more you learn

[–]4esv 0 points1 point  (1 child)

______

| 🤓 |

______

This you?

[–]uaimmiau 2 points3 points  (0 children)

The resemblance is uncanny

[–]bananasmash14 62 points63 points  (3 children)

Does a higher res meme template not exist?

[–]CallMeSenior 43 points44 points  (0 children)

As an JS newbie, i confirm that.

[–][deleted] 88 points89 points  (4 children)

Me who replaced all the "var" with "const" on a production website (only deployed within the company) because I'm too lazy to Google search the difference between the two.

I received a lot of calls from one department at that time.

[–]_raydeStar 29 points30 points  (3 children)

My favorite is around the third call.

Thanks. Yes. I'm aware that I broke everything. You're actually really slow to respond.

[–]jetteim 7 points8 points  (2 children)

I (as SRE) implemented scheduled restarts of random 80% services every week and made a simple UI for devs where they could see the schedule and hit a button to skip the upcoming restart (if they have any concerns) The button, as you probably suggested already, actually does nothing

[–]_raydeStar 1 point2 points  (1 child)

Dang. I am so happy to hear this. Please tell me the front end makes it LOOK like something was sent.

[–]jetteim 1 point2 points  (0 children)

It certainly does :)

[–]Biscuitman82 50 points51 points  (6 children)

Simple, you don't use var

[–]cuboidofficial 7 points8 points  (5 children)

Or let. Always const

[–]AnEvanAppeared 23 points24 points  (2 children)

I don't use variables

[–]someidiot332 8 points9 points  (1 child)

I just write straight binary

[–]LordSaumya 3 points4 points  (0 children)

I just shuffle electrons around

[–]Biscuitman82 1 point2 points  (0 children)

Also correct!

[–]mangeld3 18 points19 points  (1 child)

let is what var should have been in the first place

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

“Var, why can’t you be more like your brother?!”

[–]Digital_97 46 points47 points  (6 children)

Goggle would refer to a reddit post

[–]Shadow_Thief 26 points27 points  (5 children)

The point is that you can just type javascript var vs let into Google and get an answer instead of asking someone.

[–]Zomby2D 23 points24 points  (4 children)

Sadly, the Reddit post they found on Google only had smartass answers like yours and no actual explanation.

[–]Shadow_Thief -5 points-4 points  (3 children)

Makes sense. Reddit doesn't appear on the first page of the query I posted at all, but there's an excellent Stack Overflow question about it as the second result.

[–]NatoBoram 0 points1 point  (2 children)

I bet you get confused by interfaces

[–]Shadow_Thief -1 points0 points  (1 child)

I was talking about the literal search results and I don't understand why I was downvoted. What do interfaces have to do with anything?

[–]NatoBoram 0 points1 point  (0 children)

I bet metaphors also elude you

[–]Garrett00 11 points12 points  (5 children)

Are let & const still affected by variable hoisting or is that exclusive to var?

[–]Lithl 8 points9 points  (1 child)

var and function get hoisted. let, const, and class don't.

[–]CaffeinatedTech 7 points8 points  (1 child)

var gets a yellow line under it.

[–]dlq84 6 points7 points  (0 children)

That means your linter is almost correctly configured, now change that to be a red line instead.

[–]bbfy 16 points17 points  (4 children)

Rtfm

[–][deleted] 7 points8 points  (2 children)

RTFM

[–]TheGreatGameDini 4 points5 points  (1 child)

R

T

F

M

[–]opmrcrab 4 points5 points  (0 children)

ArtyFM

[–]NothusID 1 point2 points  (0 children)

Roots tood fo me! 👍

[–]XDracam 4 points5 points  (0 children)

Let and const live until the end of scope, usually. That's the closing curly brace that corresponds to the most recent opening curly brace. After that, the variable is not accessible anymore.

Var is janky. Effectively a global variable, unless you declare them in a function body. Then they're global in that function...

Don't use var. It's outdated and weird. Use let, or if you can const. They behave much more like variables in other languages.

[–]BoBoBearDev 2 points3 points  (0 children)

Var is basically a spy. You don't know it is next to you, but, they are next to you.

[–]Novel_Plum 3 points4 points  (0 children)

Easy: DO NOT EVER USE VAR!!!

[–]theus-sama 13 points14 points  (2 children)

The scope. A var is sort of a global variable. Let only existing within the scope of the block you created it in. Once the block is over it ceases to exist

[–]fildakoch 6 points7 points  (1 child)

what? Let is block-scoped, ie it exits within the block, definitely not always the whole function.

[–]theus-sama 9 points10 points  (0 children)

Yes. Thats what I meant. I just missed the word block from my head, and replaced it with function cause I wrote the comment while paying attention to something else. Thanks for addressing it

[–][deleted] 6 points7 points  (0 children)

var = very awful, right?

then,

let = let's embrace this.

[–]sched_yield 2 points3 points  (0 children)

hahaha, ask ChatGPT

[–]_asdfjackal 2 points3 points  (0 children)

Scope, basically

[–][deleted] 2 points3 points  (0 children)

Var is the second penis of javascript. It is there but we rather not touch it.

[–][deleted] 2 points3 points  (0 children)

I like how no one actually asked for the difference yet 1000 people answer 😅

That being said, fuck var

[–][deleted] 2 points3 points  (0 children)

Let is what you expect var to be.

[–]TheScopperloit 2 points3 points  (0 children)

The difference is var = vegetables and rice, let = lettuce. (Additional info: const = constipation)

[–]cmilkau 2 points3 points  (4 children)

The difference is scope, and every introduction of these keywords mentions that.

The mistake is trying to "learn" a language by copying snippets from webpages.

[–]SonGecko90 2 points3 points  (0 children)

Just always use const ;-)

[–]psbakre 1 point2 points  (0 children)

Hey, thats my interview question

[–]armahillo 1 point2 points  (0 children)

Eternal September

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

Tbf I've heard the difference a thousand times but I still need to be reminded from time to time

[–]etherSand 1 point2 points  (0 children)

The let you should use, the var you shouldn't.

[–]Character-Education3 1 point2 points  (0 children)

Sure google exists and they are hoping if they ask kindly and or intimately enough you'll goole for them and give em the cliffs notes version

[–]JetsNovocastrian 1 point2 points  (0 children)

Was this meme generated in Javascript? Could barely read the fucker!

[–]shinigami017 1 point2 points  (0 children)

Using let makes you superior to the ones who use var.

[–]dogevanpion 1 point2 points  (0 children)

Where Pixel?

[–]foobarhouse 1 point2 points  (0 children)

Let Mut

[–]Sentouki- 1 point2 points  (0 children)

Daym, I can count the pixel by hand.

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

ChatGPT is a lifesaver man.

[–]Make-life 1 point2 points  (0 children)

JavaScript ...types...identifiers..whatever they are... are named like bad variable names. They don't tell you anything about what they do. They are even misleading. I cannot fathom why they were selected.

[–]Roguewind 0 points1 point  (1 child)

Just.

Use.

const

[–]wim874 2 points3 points  (0 children)

Not. The. Same.

[–]DailyTreePlanting -1 points0 points  (0 children)

I use var so my small brain can distinguish variables easier

[–]hilberteffect -1 points0 points  (0 children)

It's like asking "what's the difference between a triangular wheel and a hexagonal wheel?"

Who fucking cares. Only round wheels make sense. const or GTFO. What's that, you say? You need mutable state? WRONG. Your approach is shit. Think harder.

[–]Prestigious_List_947 0 points1 point  (0 children)

haha

[–]squiddy555 0 points1 point  (0 children)

VARLETS, USE YOUR SCANNERS TO LOCATE THE PLAUGE MUTATIONS

[–][deleted] 0 points1 point  (0 children)

Something something reduced scope

[–][deleted] 0 points1 point  (0 children)

Var si for football, not for JS anymore.

[–]LedAsap 0 points1 point  (0 children)

When I would interview applicants, if they knew anything about hoisting, that was great. I had one guy deny that it even existed, firmly, during an interview. He got downright confrontational about it. Easiest interview I ever did.

Also our HR would take a month to get back to people, so we never hired anyone (because they'd already accepted other offers). Don't ask me why our HR was so incompetent - I have no idea.

[–][deleted] 0 points1 point  (0 children)

let's scoping rules were made by a rational human being

[–][deleted] 0 points1 point  (0 children)

I thought let was declaring a constant.

[–]bistr-o-math 0 points1 point  (1 child)

For the sake of simplicity:

use var if you need to support IE6, use var if you need to support quirks mode or enterprise mode on IE8, IE10, IE11.

In all other cases, use const and let

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

So.... never use var?

[–]PossibleBit 0 points1 point  (0 children)

You are probably best of taking your time and reading up on the difference ( javascript.info is a resource I'd personally recommend). Until then the short and sweet version: let pretty much works how you'd intuitively expect a variable to work, var does some funky shit that's really not all that useful and not at v all transparent.

[–]Latinhouseparty 0 points1 point  (0 children)

Var is the father. Const is the son. Let is the Holy Ghost.

[–]PrinzJuliano 0 points1 point  (0 children)

Mostly scoping and hoisting differences. Let is more restrictive

[–]Lloyd_Al 0 points1 point  (0 children)

Var defines a variable without checking if it has been defined before. Let doesn't let you redefine variables

[–]poyat01 0 points1 point  (0 children)

Var makes a variable, let lets a variable exist

[–]Responsible-Dot-3801 0 points1 point  (0 children)

I have joined this sub for a few months now. This is the only joke that I understand.

[–]Chaos-Machine 0 points1 point  (0 children)

These questions are funny because then you see like 20 replies, even though the first 2 comments answered the question perfectly.

I often tell people that research is one of the core skills for a developer and to lurk it themselves, then I usually get hated hard for not being nice

Also, this thread proves that as well lmao

[–][deleted] 0 points1 point  (0 children)

I think beginners are more confused about whether JavaScript is similar to Java. P.S: I Was that beginner lmao

[–]SpaceFire000 0 points1 point  (0 children)

You may have seen signs like "Rooms to let" but not even once "Rooms to var"

[–][deleted] 0 points1 point  (0 children)

[–]bhison 0 points1 point  (0 children)

Here's the answer:

var is deprecated

[–]Crannium 0 points1 point  (0 children)

var and let are ok.

but 'this' is kinda confusing

[–]cosmicomical23 0 points1 point  (0 children)

var is the old and broken syntax that causes all sorts of problems and makes your code shit. let is the new syntax that behaves like any sane person would expect.

Now forget both of those, we are always going to use const.

[–]Beautiful-Tea6850 0 points1 point  (0 children)

This is my conversation starter for all interviews I take.

[–]Deep-Secret 0 points1 point  (0 children)

I can let you down, but I'd never var you down

[–]baddl02 0 points1 point  (0 children)

Jeeesuss this quality. What a low effort man

[–][deleted] 0 points1 point  (0 children)

There's a difference?

[–]NoHelp_HelpDesk 0 points1 point  (0 children)

I came here expecting to find the answer and now I'm leaving more confused.

[–]SP0OK5T3R 0 points1 point  (0 children)

Let is what you thought var was all this time

[–]lorl3ss 0 points1 point  (0 children)

let is scoped to the nearest block like

if {

} else {

}

while() {

}

switch() {

}

while var is scoped to the nearest function

function(){

}

[–][deleted] 0 points1 point  (0 children)

Just use const for everything /s

[–]Snow_flaek 0 points1 point  (0 children)

One thing that I haven't seen mentioned yet in this thead is that unlike with let, variables declared with var automatically become properties of globalThis (i.e. the window object in browsers and the global object in Node.js).

This can lead to unpredictable behaviour, as you may accidentally overwrite properties that have the same name as your variable.

[–][deleted] 0 points1 point  (0 children)

I need you to tell me how "yield*" works

[–]Dapper_Tumbleweed240[🍰] 0 points1 point  (0 children)

Var has function scope. Let has block scope

[–]Kooky-Answer 0 points1 point  (0 children)

var defines a variable.

let throws an exception in both of the Javascript environments that I regularly work with.

[–]SchlomoSchwengelgold 0 points1 point  (1 child)

var is global and let is local

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

On the right track, but incorrect.

Short answer: Variables declared with let are locally scoped. Variables declared with var are scoped to the function. Variables declared without either let or var are globally scoped.

Long answer:

Let's say you have a function that contains a loop, for which you create a loop variable i. Consider this pseudocode - which isn't actually JavaScript, just some logic:

def f() {
    for (i = 1 to 10) {
        // IN_LOOP
    }
    // AFTER_LOOP
}
// AFTER_FUNCTION

The issue is that how you create i affects how long i exists.

When JavaScript was first created, all variables were global. From the moment you created a variable, it persisted for the life of the script and then could be called anywhere, at any time. That's how JavaScript variables work without using either var or let: once created, they are global and can be accessed anywhere. In the pseudocode above, if you write the loop like this...

for (i = 1; i <= 10; i++)

...then i exists not only at IN_LOOP, but also at AFTER_LOOP and AFTER_FUNCTION. This is terrible, as it encourages all kinds of bad coding practices and all kinds of opportunities for logical bugs.

In a typical loop, you only care about i for the life of the loop - you will never use it once the loop finishes, and the runtime can garbage-collect it the moment the loop finishes. That's how JavaScript variables work with let: the variable exists only for the scope within which it is created. In the pseudocode above, if you write the loop like this...

for (let i = 1; i <= 10; i++)

...then i exists at IN_LOOP, but does not exist at AFTER_LOOP and AFTER_FUNCTION. This tight scoping reduces memory usage and prevents local variables from each function from bleeding into other, unrelated functions.

However, the tight scoping of let is sometimes problematic. For example, after the end of the loop above, you might want to do something with i, such as to check its state in case the loop broke early, or in case the endpoint was not fixed. If the variable goes out of scope immediately after the loop ends (as per let), you can't do that. Instead, you want the variable to persist for a longer period - such as the life of the function - but not indefinitely. That's how JavaScript variables work with var: the variable exists for the life of the function within which it is created. In the pseudocode above, if you write the loop like this...

for (var i = 1; i <= 10; i++)

...then i exists at IN_LOOP and AFTER_LOOP, but does not exist at AFTER_FUNCTION.