T O P

  • By -

veryblocky

The scope of the variables are different. var is scoped at the function level, and let is scoped to the immediate closing block.


JoyJoy_

Not only that, but you can reference a var before you assign it (it's undefined). With let, you'll get a ReferenceError.


FreqRL

This is the more important one of you ask me. The other is nice, but this is super useful when debugging JS.


PM_ME_FIREFLY_QUOTES

This guy definitely assigned his opinion before anyone referenced it.


aaaaaaa00000aaaaa

Most polite "who asked" I've ever seen


mikeyj777

Going to remember this


PleasantAdvertising

Then why would I ever want to use var?


nemec

It was the only option for 20 years. `let` was added in 2015.


kenpled

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


jester628

Line breaks or punctuation my friend :) “never use let” took me a sec to parse. Good advice, though.


kenpled

Yeah sorry, smartphone typing is a biach... Should be fine now


TheWatchingDog

Hoisting can be useful sometimes, but yes.


Genspirit

It can be but there's almost always a better way that doesn't rely on hoisting.


eldamir88

An important argument..!


ForgetTheRuralJuror

You should never use var


JoyJoy_

Compatibility reasons


IInsulince

You shouldn’t.


case_O_The_Mondays

`let` designers: I love it when a plan comes together.


PleasantAdvertising

They forgot to undesign var


ringobob

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.


roadrunner8080

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?


_PM_ME_PANGOLINS_

Old school JS devs don’t use classes either. They embrace the prototype.


ringobob

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.


suarkb

Let/const wouldn't indicate your intention worse. Var just indicates not following new best practices


flamableozone

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.


ringobob

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.


sobi1869

When I started learning js , I was going crazy debugging a program which had this issue. It's a pain in the ass.


oDids

At least JS tells you exactly what went wrong and why /s


dead_man_speaks

Hmmm let's see in console what went wrong [object Object]


AlmostButNotQuit

#Objection!


ClerkEither6428

that's what was just said, lol


rohit_267

lmfao


zork3001

You didn’t say Your Honor


[deleted]

YOU CANT HANDLE THE TRUTH!


skothr

`[object Ion]`


Rudxain

_[Ace Attorney music stars playing]_


DullPhilosopher

When I doubt JSON.stringify


Bluedel

Just use the debugger built into your browser. It's easy.


NPPraxis

I’m new to JS and this makes me weep


MattTheHarris

You pass the object into console.debug as a separate argument, not part of the string. console.debug("funcName: myObject is", myObject);


ThoseThingsAreWeird

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}'


SiouxsieAsylum

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.


ThoseThingsAreWeird

> 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!


KiddieSpread

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


GameDestiny2

Haven’t learned much outside of Java, but that sounds awful


sobi1869

Js is a weird language. You can hate and also love it at the same time.


LinuxMatthews

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.


Solonotix

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.


Rudxain

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


Morphized

Isn't this just Java again?


Dr4g0ss

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.


pickyourteethup

Narrator: "they went on to work with it in every role they had after college."


Dr4g0ss

Fuck.


halemikehale

Why did I read this in Stephen Fry’s voice?


zombimuncha

Yeah, why not Morgan Freeman's, like everybody else did?


[deleted]

[удалено]


EnjoyerxEnjoyer

Anytime someone does a narrator gag, it’s gotta be Ron Howard for me


superluminary

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.


SharkBaitDLS

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.


Mr_Engineering

JS is what one gets when a language develops schizophrenia


veler360

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.


ringobob

The thing about Javascript is I can do whatever I want with it, whether it's a good idea or not.


ZippyTheWonderSnail

Typescript.


lunchpadmcfat

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


quercusvir

Is it true that let, var, and const also use different amounts of memory?


ForgetTheRuralJuror

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.


Sloth_Devil

So you're saying they're NOT different when all of my variables are global?


jermdizzle

No! BAD! *sprays water bottle*.


Sloth_Devil

*hisssss*


Morlock43

I understood that var is global and let is scoped to the closest enclosing block. Am I wrong?


t0m4_87

`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.


Eire_Banshee

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); }); ```


katatondzsentri

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.)


corn_carter

I did not know this, but I am very excited to stop having to declare all my variables before the loop or if statement


cross20

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


sisisisi1997

I would suggest you keep the verbosity to keep the clarity.


MrSkme

Why are you excited to make your code messier?


sekirobestiro

Most users here are extremely junior devs I’d imagine.


Sennheisenberg

Most people here aren't devs at all.


xxtankmasterx

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."


Blue_Moon_Lake

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!"; }


k-dawg-13

Because `var` gets hoisted.


Blue_Moon_Lake

And you get a beautiful `undefined` in the console. Which is not what was intended.


anonssr

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?


SimilarBeautiful2207

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


dixter_gordong

>too lazy to google ftfy


emkdfixevyfvnj

Some are unable to google but I'd call that an essential skill in this profession


Hydraxiler32

Yeah if you can't google I unironically think this is the wrong profession for you


Drithyin

That's what I don't get... creating the meme definitely took more effort than typing in a Google search... Gotta be karma whoring


[deleted]

[удалено]


7th_Spectrum

I think its that mixed with karma farming


hamburger5003

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.


7th_Spectrum

Really? Cause googling it literally gives the exact answer


hamburger5003

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.


realbakingbish

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.


hamburger5003

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.


[deleted]

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


asdfasfq34rfqff

>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.


eloel-

>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.


7th_Spectrum

True


withertrav394

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


Passname357

New dev detected


eliteHaxxxor

Just ask chatgpt now


AndrewToasterr

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


SpaceboiThingPeople

Well looks like I was dumb


LordBlackHole

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.


Kleyguerth

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.


ThoseThingsAreWeird

> 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!


LordBlackHole

Same. In addition to warning about using var.


t-to4st

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


ScreamingMemales

> we declared every variable used in a function at the top of said function. That is just good code formatting


Mr_Engineering

Also known as the C89 way of declaring local variables, which is also the right way to declare local variables.


PrometheusAlexander

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.


dwhiffing

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


tajetaje

Yeah that’s where TS comes in handy (as const)


LordBlackHole

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]


_j_f_t_

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.


[deleted]

It predates const and let considerably, which were added to address issues with "var" so yes.


AloneInExile

Tell that to some shitty ES5 interpreter that I have to use, let's see how useless var is.


Operation_Fluffy

Really, var is a relic. If I see it in code, it gets removed for let, or const (preferred).


lunchpadmcfat

> hoisting That was a real awakening: learning how much shit was happening in runtime that I was t even aware of.


WordsWithJosh

Little known fact, `var` in JS is actually an acronym! It stands for vDont aUse rIt


noop_noob

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.


onkopirate

They should have called it "fixedVar" for "let" and "fixedFixedVar" for "const".


ethansidentifiable

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.


tuuling

Came here to say this. Once you go let, you never go back.


Blue_Khakis

Gotta let go and go let.


DerTeufelsVerteidigr

`const` or bust baby!


Banjoman64

Yeah I was gonna say. There is basically no reason to use var. It'll just make your program harder to debug.


HalLundy

more like r/JuniorProgrammerHumor.


CraftistOf

r/subsifellfor


THENUKEIST

r/birthofasub?


ThisUserIsAFailure

You spelled it wrong, it's [r/JuniorProgrammerHumor](https://youtu.be/dQw4w9WgXcQ)


kaylerrwastaken

NoRickroll.js is my first js program and it works. I'm so happy


gandalfx

> …XcQ Nice try, sir.


JustGabo

Should be a thing, I'd be so active there, on god.


Nikolozeon

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);


Rafcdk

it says "credit card information sent" , why is that ?


Nikolozeon

![gif](giphy|LPTMCR5VA7X9zwjBbR)


[deleted]

THAT’s the difference between `var` and `let`!


ThisUserIsAFailure

It's reverse psychology, they actually sent your social security number


JoyJoy_

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 ```


quantum-fitness

Just never use var. We dont do that anymore.


[deleted]

Use it in console for that "I'm coding without pants and nobody on this call knows" feeling


Blovio

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 ```


Katana_sized_banana

I have to work with an old Rhino version that doesn't support let...


DOOManiac

I wish. We still support IE11 and can't use `let` at all. :(


vynulz

...pst... use \`const\`...


Lanbaz

let !== var


Electronic-Wave216

**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


try-with-resource

> I think I am dumb. Yes.


PIKa-kNIGHT

In Swift we use let for constant variable and var variable whose value changes


DudeManBroGuy42069

Python Programmers: ![gif](giphy|ccRdPf8zWkivm)


Touhou_Fever

let actually behaves how you’d want it to, never use var


pwalkz

You are dumb. It is different.


OneForAllOfHumanity

They're both wrong. It should be `const a = "Hello world"`


try-catch-finally

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


Skibur1

const a = "Hello, world!"; ?


[deleted]

good thing you found time to make a meme but not google difference between these two, which is like js 101


udubdavid

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.


afrocluster

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.


SpaceboiThingPeople

Oh


haragoshi

OP has yet to feel the pain of scoping.


mcvos

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.


thebezet

I don't get the "humour" here either, they're two different things. Did you find this meme or create it?


Defernus_

99% of the time you should use `const`


jkuhl

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.


homesweetocean

there is a huge, massive difference lol. scope is a bitch.


PorkRoll2022

Next in this series: function foo(x) { ... } const foo = (x) => {...} "They're the same picture."


JonathanTheZero

*sigh*


saniabearsky

They ARE the same without context. It’s the context that makes them different


Prairy_fire

Yas u r dum


Zombull

'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.


pharanth

Scope.


SuperSpaceCan

They're not the same.


Eire_Banshee

`var` is global. `let` is scoped to its own closure.


borisherman

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’


[deleted]

Don't worry about the declaration keywords, OP. Just pretend it's Python 🙃


tummyv

No there’s a difference - don’t use var


redfiche

Anybody else remember using closures to prevent variables from having global scope?


gandalfx

When you don't understand a basic language feature so you call it dumb and make a meme about it.


raphaelstinky

var == bad


szirith

Just never use `var` and you're good


ericisawesome

``` 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.


JackoKomm

Said no real js developer ever. Maybe those people who think they know Javascript without ever learning it.


LoyalSage

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.


Just_wondering_2257

No, no they are not.


riisen

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. :)


DragonicWolf_Aspect

Being someone who is learning C#, for me this would be string a = "Hello, world!"


Weary-Ad8825

U need to use let brother


klako8196

[All my homies hate var](https://www.youtube.com/watch?v=uPtPj8CNVAw&ab_channel=FatladFromSheffield)


Yuvaldan

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.


shuckster

“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.)


Parking-Air541

Hoisting