Let’s play… Does your code suck? JavaScript Variables Edition
HTML-код
- Опубликовано: 22 авг 2024
- Can you tell which code example is bad? Learn the subtle differences between variables in JavaScript by comparing let vs var.
Learn more about JS in my full course fireship.io/co...
#javascript #programming #game
You had me at "does your code suck".
Yes it does.
if you don't know than say it so i can skip you
This is the sign of true maturity in software engineering
I gave it a 50/50 till he followed up with JavaScript. Then 100% yes.
But if you know it sucks then you are better than half of the coders
Hired.
I mostly watch JS videos like this to continue validating why I don’t do web development.
Then what do you do ?
@@spunzel851 internal desktop and CLI tools development, mostly.
Same 😂
But web dev is fun. Though I can't seem to get hired
@@hikari1690where are you located?
I've avoided using var without knowing what it does, but this really helped me understand, thanks!
This is not the only reason why it's awful. It also has some real awful scoping issues.
@@CottidaeSEA I think the scoping issue is what the video was talking about
@@michawhite7613 It was only about one of the scoping issues.
Use const until you absolutely can't.
@@michawhite7613 Unsure if I just can't see my reply, but basically, the video doesn't go into all of the scoping issues.
Gotta love getting a runtime error for something which can be statically checked.
That's just interpreted languages though?
@@arnerademacker yeah, it's an unfortunate but necessary evil in order to have all the other niceties that runtime interpreted languages have.
@@Templarfreak What kind of niceties do you have in mind? Most of the ones I can think of aren't necessarily tied to interpreted languages, but I'm very possibly forgetting some.
@@arobie92 nothing is tied explicitly to any particular interpreted language, no, but that's because any language can be runtime interpreted if you are ballsy and brave enough. at which point, any language can have the benefits of doing so. you get advantages like VERY fast feedback, possibly even basically instant if you can reload the code without needing to reload an entire program.
@@TemplarfreakAh so the primary benefit you're getting at is a managed runtime? I'll definitely agree that hot reloading of modules, while technically doable in compiled code, is significantly easier in managed languages.
As a C/C++ guy that's a big "Holy shit people live like this?!" thing.
Tbf, I could say the same about declaring the var typeOf on init. Or having to allocate memory. You and I live on strange worlds, but the other is far stranger.
No, we just don’t use var lol. I’d much rather this than C/C++ 🤢
@@12Fakeaccount you don't need to allocate memory always
its when you want more control over it that you do
C/C++ really allow you to access/fu*k up, lower levels of the system
you can divide by 0 and it continues the program for ever (Alhtough compilers and windows can now catch it)
both have their uses
JS for web
C for Win native applications etc
@@RealNaisuCinema C/C++ makes you a powerful wizard though
Fr
One of the most important lessons I learned early in my career as a SWE was that exceptions are good. The way they were taught in college, I felt like my job was to make sure nothing ever threw an exception and halted so I ended up with try/catches and log messages everywhere. No: if something goes wrong, you want to throw a good exception and let it break
When do you decide to not let it break?
Also do you think that the software education you got in college was poorly taught?
And did the professors usually have no industry experience?
@@skyhappyyou don't let the code break when there's scenarios in which you know it's gonna break so you want to control what happens after the errors come knocking. That's why it's called error handling, blindly catching any and all errors is just a debug nightmare
If you're going into development you'll eventually deal with some application that has a server, and many clients.
In this scenario you'll have to make everybody talk to eachother, and it's not about if, it's about when a connection error will happen.
At that point based on the reason of the error happening you might want to have the code try again, notify the user and ask them to check their connection, or kindly tell them that your app is facing some challenge and they should come back at another time
My personal go-to: use "const" for everything unless you need to mutate/set the value - then use let; even then consider using a new const if you can. Don't touch var like it's got an infection, I can't remember the last time I had to use it.
I wish more C/C++ writers were const correct whenever possible.
Unless you need to mutate?
You can mutate arrays and objects even if they are const,
const arr = [10,20]
arr.push(30) works
@@adityaanuragi6916just becaude you can, doesn't mean you should. Const keyword tells something to the code reader.
This. Like kids game. You ever write var you die. Never ever do it.
Rust programmers be like
Ah, the good old days of tricky js interview questions.
It’s still used for entry level interview. I remember having a hard time explaining “why var sucks” just because I proactively chose not to use it lol
Yes very tricky. Using variable before defining it. Would just spit on the face, laugh and leave if that wouldn't be the sought answer.
that is not tricky lol. most js interview questions are harder than this
i love to use const first and then adjust later with let, if needed (like in Rust, having immutability first and then adjust).
You can't override a const. Const means constant. As in cannot change. You have no idea what you're talking about.
@@Dylan_thebrand_slayer_Mulveiny i never said that i can override const :D i've just said that i would use const first, and adjust later with let.
Well try this:
For placeholder variables like arr, obj etc use let because along the way they'll be updated
const for like loops or callbacks fxns
I can't tell because I can barely see the screen when RUclips puts buttons, labels, and other bs all around and blocks everything.
How small is ur phone?
@@redrush-hp9li size is not important
@@andreujuanc tell this to your GF
Someday the video will just be an animated background for a grid of buttons.
i have the same problem both on the phone and on the computer
"does your code suck"
I fixed a display issue the other day by adding a 0ms setTimeout.
Technically that actually does delay your code a bit. I'm not sure if it's a microtask or having it to somewhere else in the queue. But there is a whole set of things that occur when you set timeout to zero and promise and immediately resolved it. Those like an entire algorithm for how to handle those things
I once fixed buggy code at a new job. Previous Dev tried to fix issues by using multiple timeouts. Page ended up loading 3 seconds faster. I got a 13k$ bonus that year. :)
So I guess I have to thank guys like you.
"I have no idea WHY this works, But it does, So just don't touch it"
So basically running code in new thread ?
@@Lumither-404 There is only one thread in a browser. Using setTimeout will put its callback function in the event loop stack to be called later. Sometimes this delay is sufficient for code this callback function depends on to be evaluated. Search for "Race condition in JavaScript".
Thanks for letting me know before I end up messing up in the future 😅
just never use var, i've never found a reason to use it.
@@squidy2902yup there is no legitimate reason to use it, if anyone at any point tells you that there is, they are wrong 😂
Var and future)))
don't worry you'll still mess up, all is well : D
Praise Cthulhu, and his favorite programming language, JavaScript.
ah that makes sense. this feature probably only works for a being such as Cthulhu who doesnt care about the constraints of spacetime at all.
No, my code does not suck. Javascript does.
I respect and greatly appreciate your work so much. I'd love to have a countless number of these as I start my journey into JavaScript. Either way, THANK YOU!
Good one, I knew the var would hoist but I didn't know the value assignment would be executed after the log. I think even with a 100 years of JS experience one can be surprised from time to time.
The TDZ is temporal, as opposed to scope-based. i.e. You can use your variable before it's defined in code order, as long as by the _time_ hou need it, it's been defined.
function logX() {
console.log(x)
// ☝️ refers to the x below thanks to hoisting
}
let x = 15
logX() // prints 15 just fine
one javascript snippet a day keeps the motivation to do webdev away 😭 wth is that shit how can a closure capture a variable before it is defined (i know you explained why but who tf though it’s a good idea lmao)
That's very interesting, thanks for sharing this
@@LosFarmosCTL Thankfully scoped variables and arrow functions exist so you can just pretend this doesn't.
@@adam7802 You're misunderstanding. This applies _specifically_ to scoped variables (TDZ only applies for let and const variables). And it's _more_ relevant if you use arrow functions. e.g.
console.log(plus(5, 3)) // prints 8
function plus(a, b) {
return a + b
}
Compare to:
console.log(plus(5, 3)) // TDZ error
const f = () => console.log(plus(5, 3))
const plus = (a, b) => a + b
f() // works fine
@@kebien6020 I meant more in general rather than this specific issue. Although I didn't know that would work... Javascript is such a mess.
The error is not 'a is not defined' it will be ' can not access a before initialisation '
It’s not the code that sucks at this point it’s JavaScript itself
It's the necessity for backwards compatibility that makes it suck. Programmers just didn't know how to write clean code back in the early days :)
have a decent linter and you'll stick to a subset of js that doesn't suck
Always has been
What do you mean ? the code is non-sense but JavaScript handled it quite well throwing reasonable output.
It's bad, but I had a C++ class and it felt like 80% of the language is forbidden territory.
2005 called and he wanted his var back
currently this comment section is the only thing that is worse than var.
On second thought-
Not me realising this was the error I spent several hours on a couple of months ago (and gave up on).
Thanks Fireship, very cool.
I know nothing about javascript and just guessed that var does something funky based on my minimal Rust experience.
I started learning JS a few months ago and initially would only use var. I thought it was very convenient to make everything of global scope. But I stopped using it completely in a month or two because I realized its actually more convenient to have variables only take local scope.
Been using const almost exclusively since then.
Btw, I like JS. I liked it from the start. Yes, its very messy and you get the impression that it got more features without being made 'neater', but its really versatile and powerful. And yes, my code does suck. I make things too difficult. Whatever practice/learning I'm supposed to do, I think of some way I can make it ten times more complex, just to do some extra stuff.
Thats the way my friend. We all had this journey until we get to know stuff better ^^ In coding, skill comes with experience
Totally quitting var keyword and using typescript is one of the best decision in my life
I learned about hoisting variables in my compilers class. This is a really good explanation!
I'm not quite a js dev, but I might be coding js soon and definitely needed to know this
Us C devs know to always declare and define your variables before you use them.
gotta start doing that for pointers too man
Yea sure, but if your code changes later you might miss a spot a variable is used - which should result in a compile error , but seems like JS is just 'fine' with it.
I've always put the declaration first and I don't typically use languages that care. It just feels wrong, like using someone's name before they've introduced themselves lmao
Aha!! I got it right! I’ve been studying JavaScript for like 7 hours total! I am so fucking smart!!!
I always use let ever since it became popular, but now I see why it got popular. I probably don't even realize how many headaces I've dodged
Not many actually. You just avoid 1 concept
First time i actually already knew this and actually understood what you were talking about!
Does your code suck ❌️
Does your programming language suck ✅️
nice, I knew about the var hoisting thing but didn't know that the values didn't get hoisted along. makes sense why they updated it
You cannot get value before you assigned it. Common sense.
Using "let" when programming makes me feel like I'm back in the late 70s programming in BASIC.
Need more of this content
Python does hoisting, too, and you can't turn it off. I'm actually really happy I knew this.
what are these comments man 🙏
Right? Lmfai
This is my drug. Like a continuation of my computer systems class where I first learned how scoping works on a hardware level
"Temporal Death Zone"; fucker got me with that Loki suff
Brother this isnt "does your code suck"
Its "does Javascript suck ?"
And ill be proud to answer YES YES IT SUCKS
Seems like you know almost nothing about js, am i right?
No one uses var anymore anyway there's nothing it provides over let or const to justify it's usage.
Functions also get hoisted, but only if declared with the function keyword.
nice! I passed. I was immediately like.. oh that's undefined!
a general rule, scopewise, const > let > var > global.
but var and global do have their use cases.
the example is so simple that const is the "right answer" and both samples "suck" 😜
Finally I LEARNT what the difference is
Fun fact. "let" variables also get hoisted, but you cannot access them before they are assigned a value. If you would define a function using "a", then define "let a = 1", and then call the function - no exception is thrown.
This one was easy peasy... I come from a time where there was no let and const, only var... So those quirks are basically ingrained in my soul now
JavaScript used to suck so bad
Lol. Thanks for articulating why I stopped using var. I got hoisted too much for my liking and tossed that out a while back.
" that can easily debug" get me😅
What a great word. Hoiiiiiii-sted.. Love it. I actually ran into this issue yesterday. 😆
I've never called myself an experienced programmer, but I guess my recent browsing through JS documentation paid off because I was surprisingly able to figure out what the code would do lol
I learned something today... I knew that let would throw an error, but didn't knew about the var throwing the declaration to the top and the reassigning it on the spot.
Good to know this.
I knew it was B
Simply because var is automatically stupid
Long long time ago there was no let in JS, and everything was normal. Now you have choise that causes different behaviors. It took a long while to shift myself from var to let, but because C# still uses var just like JS now uses let...
Hoisting is important in jetpack compose in Native Android
Bruh swift is like: THE ERROR IS *RIGHT THERE* do you SEE IT???!!!!!???!?!?!??!!!???
I know next to nothing about Javascript, so at first I was shocked when it said the first one had an error since that was the one I picked, made a lot more sense when I turned out to be wrong
Ya know… when I hear JS being a trash fire of weird language mechanics, I used to think they were exaggerating.
Started learning JS just 2 days ago, and I never really knew why everyone was saying not to use var to set variables. It seems much more telling in its name, so you would think its better. Good to know I guess.
Ngl the RUclips shorts interface is shit. I didn’t realize the difference cuz “var” was partially covered, and there’s no way to hide the buttons over the video
This is cool. I know JS and understand hoisting. I just subconsciously never use 'var' and instead use 'let' or 'const' depending on what I need.
the bottom part, cant really read anything because of this great gui by youtube covering about 60% of the acreen
The “const” keyword made an impression on me, but “let” (vs “var”) never really did.
So, my code does suck. And both examples in the video are still broken.
Thanks for pointing out the error diagnostic differences, though. The “Block scope” (in giant oversized functions???) aspect of “let” never mattered much to me, as someone who did a lot of Pascal, and some Lisp, etc, back in uni in the 80s, dragged into C and its bastard spawn in the 90s.
And I would rather do Clojurescript than Typescript, but rather still have a dependency on neither. Bah, humbug! 😁
When a language is less consistent and more confusing than literal undefined behaviour, you know you've messed up somewhere.
Not really "after the declaration" but "after the declaration has run"
If you have a function above the declaration but it only gets called after the declaration, it works fine
Saw var, instantly knew the answer
I was thinking, "Hm, Error?
But isn't that what's supposed to happen?...
Hmm..."
"does your code suc-"
yes it does
I was right! I guessed the bottom one. I'm still a coding beginner, and I didn't know about the hoisting. Good to know!
Not needed there is no var in modern js development
I just define everything I know I use right at the top, even abouve (and outside, obviously) functions, until they need to be changed
One shouldn't even use "var" anymore. The keyword "let" is more cool.
The Price is Right theme still bumps
Nah I'm good. I have never in my life expected a variable to hold a value before declaring it
That's why it's always suggested to either use let and const
I like and doslile js at the same time. It's easy but it also lets a lot of no go stuff go through until it breaks at some point.
We need more videos like this .
You want to get knowledge about 10 years ago js?
This is why I've started to use let instead of var whenever I'm coding in JS.
"Does your code Suck?" You ask, but you already had the answer when you said "Javascript edition"
YOU JUST SAVED ME HOURS.
I love JavaScript because windows is my daily driver and discovering little weird hacks and quirks of the language reminds me of getting windows to work and also horse-climbing mountains in Skyrim.
finally a js developer who doesnt root for silent errors
Idea for new game show: This Code Isn't Right. Keep the same music from The Price is Right
I knew which one was bad because of lint :) But I didn't know why!
I had a fun issue where someone used "var" in a for loop for the iterator variable.
For some wild reason, some code outside of the loop also tried to use the iterator variable.
Then, the code editor changed a bunch of vars to lets and everything broke 🙃
When in doubt, use const.
There's a very annoying class of JavaScript developers who internalized the lack of errors and will insist that the fewer incorrect code samples produce errors, and the later those errors surface, the better.
that log before the variable is making my java brain hurt
And here I was thinking that bar just means scoped variable
Dayum I just started to learn coding and I'm already full of coding shorts, I'm happy tho i don't understand 90% of them aha.
when I see a JavaScript code with var statements all over it I run from it as fast as I can 😂
This explains the time i fixed something by switching let to var 😂
you can rename to Let's Play: Do you use ESLINT
Oh cool. I only stopped hoisting to assuage linting rules, nice to know there's an actual reason.
Every lint rule has a reason behind it.
you can still debug the undefined thing (at least in Firefox, I don't use chrome)
im happy I actually knew that felt wrong, just dodnt know why
Chatgpt told me this the other day and I thought it was hallucinating
Temporal dead zone is kind of a sick name
I guess you just found us a use case for var, since I have been avoiding it ever since let and const came out.
Fuck... I got baited. Nice work my man. I'm all like the top one the top one.
JavaScript's lava flow quirks are what make it fun. Especially compared to C++, where template metaprogramming has made everything just...just awful.