Closures Explained in 100 Seconds // Tricky JavaScript Interview Prep

  Рет қаралды 328,764

Fireship

Fireship

Күн бұрын

What is a JavaScript Closure? Learn the how closures allow functions to "remember" outside their local scope fireship.io/tags/javascript/
#js #programming #100SecondsOfCode
🔗 Resources
MDN Docs developer.mozilla.org/en-US/d...
My Favorite Closure Explanation stackoverflow.com/a/36879264/...
Interview Question dmitripavlutin.com/simple-but...
🤓 Install the quiz app
iOS itunes.apple.com/us/app/fires...
Android play.google.com/store/apps/de...
🔥 Watch more with Fireship PRO
Upgrade to Fireship PRO at fireship.io/pro
Use code lORhwXd2 for 25% off your first payment.
🎨 My Editor Settings
- Atom One Dark
- vscode-icons
- Fira Code Font

Пікірлер: 410
@theultimateshield5133
@theultimateshield5133 3 жыл бұрын
click the f**king button man its his f**king dream😂😁😂
@dfsgjlgsdklgjnmsidrg
@dfsgjlgsdklgjnmsidrg 3 жыл бұрын
no i wont
@anmolmaniyar6868
@anmolmaniyar6868 3 жыл бұрын
Plot twist: it's an erog- Nvm
@chiragsingla.
@chiragsingla. 3 жыл бұрын
clicked it from all my alts
@baibhavvishal362
@baibhavvishal362 2 жыл бұрын
Just clicked because u asked nicely 🤪
@ihavetwofaces
@ihavetwofaces 3 жыл бұрын
"If you ever find yourself faced with a question like this, the best thing you can do is talk through the code slowly and [demonstrate the knowledge you do have], so they know you're on the right track, even if you don't come to the right conclusion." Hands down the best tip for a technical interview of all time. I've assisted with coding interviews before, and the absolute worst thing you can do is shut up, say nothing, or say "I don't know." Even if you really don't know, show what you do know, ask questions, and try to apply what you have to the problem. That will earn you a tip or a hint or a rhetorical question, and that may lead you to the right answer. When I interviewed for my first job, I got two of three questions mostly wrong, but I was actively participating, asking questions, trying to work things through, etc., so I got the position.
@ko-Daegu
@ko-Daegu Жыл бұрын
That doesn’t fully apply in todays world we’re competition is in all times high Talk thru your solution and get the right answer is now expected The curve to get an entry job got even steeper and it keeps getting this way
@Jubinmail
@Jubinmail Жыл бұрын
Good tip. But don't expect a call back.
@jessh4016
@jessh4016 10 ай бұрын
@@ko-Daegu I mean, of course being an expert in everything is the best. But if you don't know the full answer, talking through what you DO know is still infinitely better than just getting nervous and clamming up.
@devsauce
@devsauce 3 жыл бұрын
Christian Bale === Closures. Got it Jeff.
@naythaniel
@naythaniel 3 жыл бұрын
Christian Bale === actor Patrick Bateman === closures Christian Bale !== Patrick Bateman
@PickleSurpriseVEVO
@PickleSurpriseVEVO 3 жыл бұрын
But American psycho ends without closure
@danieljoaquinsegoviacorona1734
@danieljoaquinsegoviacorona1734 2 жыл бұрын
Whoever thought of closures is a psychopath for sure! lmao
@deepkhamaru1154
@deepkhamaru1154 2 жыл бұрын
Well he did give closure to Batman! So... You're one hundred percent right!
@CarlJohnson-iv7sn
@CarlJohnson-iv7sn 3 ай бұрын
Adding sigma Patrick Bateman with closures (hard interview topic) is such a chad ohio enjoyer thing to do. I'm sure Jeff was mewing while he made this video.
@LoveThatSceneChannel
@LoveThatSceneChannel 3 жыл бұрын
One day I will watch beyond the 100 seconds, and then I'll get closure
@MiguelQuinaRibeiro
@MiguelQuinaRibeiro 3 жыл бұрын
This comment made me rethink my life 😱.
@xunxekri
@xunxekri 3 жыл бұрын
Shame it's not on Clojure
@magne6049
@magne6049 2 жыл бұрын
genius comment, multiple meanings, you are Christopher Nolan.
@LoveThatSceneChannel
@LoveThatSceneChannel 2 жыл бұрын
@@magne6049 I see you 😂👍🏻
@jordizweden5201
@jordizweden5201 3 жыл бұрын
when you said "click the f*ckng button" you had me
@Marcosmapf
@Marcosmapf 3 жыл бұрын
About the question, it's also tricky that it prints 3 3 3 instead of 2 2 2 since the loop compares i to less than 3 instead of less or equal to 3, but it makes sense considering the i is incremented after the last loop (i++) and the last value evaluated is 3, which is false for the iteration but still a valid value for i
@adeshas83
@adeshas83 2 жыл бұрын
It shouldn’t increment because the for condition has 2 rules that should prevent it from increments.
@MohamedHaddi
@MohamedHaddi Жыл бұрын
@@adeshas83 after the third iteration ends (when `i == 2`), `i` is inceremented to 3 then is checked against the condition `i < 3` which evaluates to `false` because now `i == 3`. so the loop ends there.
@migueljara9399
@migueljara9399 Жыл бұрын
Thank you for clarifying that. I was trying to wrap my head around it.
@ToddsDiscGolf
@ToddsDiscGolf Жыл бұрын
Yes I spent a couple minutes staring at the problem on pause until I figured out why it printed 333 instead of 222. I’m glad I’m not the only one
@TsoiIzAlive
@TsoiIzAlive Жыл бұрын
Tricky but not really tricky
@KoyFoster
@KoyFoster 2 жыл бұрын
3 years writing JS and I never took the time to look up the diff between let and var. Thank you very much.
@dervaken3902
@dervaken3902 Жыл бұрын
nobody uses var nowadays lol
@Kivencito
@Kivencito Жыл бұрын
@@dervaken3902 hi, i just started programming and i picked js for that. Would you please explain why is that? that nobody uses var? I use it quite often. Thanks!
@kaoticgamer1404
@kaoticgamer1404 Жыл бұрын
@@Kivencito from what I know, it's better to use 'let' because if you use 'var', it can be easily changed by any function because it is global, and that can lead to unexpected results. It's better to use 'let' because it encapsulates your data and limits the scope, so that makes it easier to know what is affecting your variable and to know the outcome. Also use 'const' if you know the variable won't change.
@idc20627
@idc20627 Жыл бұрын
@@dervaken3902 should still know what it is, what if you're working on legacy code. Problem is, most people are in it for the money and not the knowledge and then you wonder why bob knows so much and you know just enough to get a job and stay at that junior role for life.
@NoidoDev
@NoidoDev Жыл бұрын
​@@dervaken3902 😮 Why would you have your functions be able to access every variable outside of it?
@jkjoker777
@jkjoker777 3 жыл бұрын
the trick question at the end would still log 3 three times even if the setTimeout time was set to zero. setTime is an api that does not run in the current js runtime
@Fireship
@Fireship 3 жыл бұрын
Good point, I explain why that happens in the event loop in this video kzbin.info/www/bejne/rJ-WpaBmptqip6c
@omaribbrahim
@omaribbrahim 2 жыл бұрын
I don’t think this is a trick question. I am new to Javascript and had to wreck my head to wrap it around this the first time it popped up in my code.
@okyanusozsahin3439
@okyanusozsahin3439 2 жыл бұрын
Thank you!
@jkjoker777
@jkjoker777 2 жыл бұрын
@@omaribbrahim that’s kinda the definition of a trick question ; non intuitive answer
@dhkatz_
@dhkatz_ 2 жыл бұрын
Current JS runtime? That's some confusing wording. I think what you mean to say is that setTimeout will at minimum wait until the next tick of event loop plus whatever delay you set. Furthermore, if there are any other messages waiting to be processed by the loop (like other setTimeouts) then your callback must wait more. So a delay of 0 will just wait until the next event loop tick at minimum. Depending on what you're doing this could be far longer than 0 ms. The timeout is only the *minimum* guaranteed time.
@pavanakumardr152
@pavanakumardr152 3 жыл бұрын
you deserve more than 1 million subs 😊😊
@TheresAStarman21
@TheresAStarman21 3 жыл бұрын
Last time I was this early, fireship was not using firebase.
@justingolden21
@justingolden21 3 жыл бұрын
Hi Earl
@lars2299
@lars2299 3 жыл бұрын
@@justingolden21 lol
@GavHern
@GavHern 3 жыл бұрын
wasnt his name "Angular Firebase" before tho?
@TheresAStarman21
@TheresAStarman21 3 жыл бұрын
fixed it.
@deebakapadia
@deebakapadia 2 жыл бұрын
@@GavHern Yep. Then Google bought that domain. Idk how that happened lol
@kalvinpearce
@kalvinpearce 3 жыл бұрын
JavaScript is a fever dream 👀 Thanks for taking us further down the rabbit hole
@spythere
@spythere 3 жыл бұрын
Just wait till you get to TypeScript...
@user-xh9pu2wj6b
@user-xh9pu2wj6b 3 жыл бұрын
@@spythere typescript is less of a fever dream though
@spythere
@spythere 3 жыл бұрын
@@user-xh9pu2wj6b Yeah, it's like a obscure dream but with some good aspects (like Intelisense or types) :D
@gourabmukherjee2169
@gourabmukherjee2169 3 жыл бұрын
This channel is my favourite. Best content + No bullshit = fireship ❤
@bilalchami1
@bilalchami1 3 жыл бұрын
How convenient. Was working on a memory optimization issue today related to this topic, and here you are nailing it and explaining everything in ~5mins Thanks 🤘🏼
@namanagarwal690
@namanagarwal690 3 жыл бұрын
I don't how you do it but your content is amazing. You sometimes cover subtle details that anyone would overlook.
@13hdni37
@13hdni37 2 жыл бұрын
I love your 100 seconds videos, especially when they go beyond 😊. Keep up the good work!
@DH-qu8wh
@DH-qu8wh 3 жыл бұрын
I finally get it! Thanks for always having concise explanations of complex concepts!
@shivamjhaa
@shivamjhaa 2 жыл бұрын
This is literally the best video explanation video on closures. I keep coming back to this. This explains why things we take for granted (for ex, debounce in lodash) works. Thanks a lot man.
@xrr-1
@xrr-1 3 жыл бұрын
Another way to log 0,1,2 with `var` is by forming a closure using an IIFE A good way to solve if the interviewer doesn't allow you to use `let`
@Arcwise
@Arcwise 3 жыл бұрын
Your presentations are truly awe-inspiring. Despite their short length, I‘m sure the more thought went into them to extract the bare essence for us to digest, with intentions to pique our interests and to motivate us to go in-depth on our own. The appreciation for your viewers valuable time is reflected though the content‘s succinctness and demonstrates self-awareness in this era of mind regurgitation incentivised by the algorithm.
@gherbetto
@gherbetto 11 күн бұрын
Two years ago you didn’t have 2 mil and now look at you! Great KZbinr you are
@boiimcfacto2364
@boiimcfacto2364 3 жыл бұрын
I've said this before, I'll say it again - YOU'RE THE BEST when it comes to these kinds of tutorials.
@Computeshorts
@Computeshorts 2 жыл бұрын
Been trying to understand closures for ages and this video taught me them in 5min well worth it. Thanks.
@mayanxoni
@mayanxoni 3 жыл бұрын
Man with this content, you deserve millions of subscribers!
@cryptodive7175
@cryptodive7175 3 жыл бұрын
This is one of the best channels, short & to the point.
@ahmaddynugroho
@ahmaddynugroho 2 жыл бұрын
These 100 second series really awaken my motivation. Thank you
@surlysmiles
@surlysmiles 3 жыл бұрын
Love getting that interview question right. Makes me feel like it's time to move past js
@danvilela
@danvilela 3 жыл бұрын
Best closure explanation i have ever seen! Good job
@Krzysiekoy
@Krzysiekoy 2 жыл бұрын
Some people in the comment suggested that you could still use var and log 0, 1, 2 by doing IIFE (immediately invoked function expression) and that is a common solution when you are forced to use var (for example, during an interview). I've been coming back to this video from time to time as my understanding of JS improved, and I have found another interesting solution with var while exerimenting: for (var i = 0; i < 3; i++) { function log(){ console.log(this); } setTimeout(log.bind(i), 100); } So, basically we create a bound log function, and we pass the value of i variable in the current iteration as "thisArg".
@Thuckmyath
@Thuckmyath 2 жыл бұрын
This is LITERALLY my favorite KZbin channel right now!!!
@arghyaguha6356
@arghyaguha6356 10 ай бұрын
This is prolly the best explanation of closures there is!
@spaaaaace8952
@spaaaaace8952 8 ай бұрын
What a legendary video. It took me around 10 minutes of pausing and rewinding just so I could absorb the information.
@suraj-ram7488
@suraj-ram7488 3 жыл бұрын
Love the concise teaching style
@tinpham6413
@tinpham6413 3 жыл бұрын
I learned closure yesterday and you release this vid. Awesome
@ChrisAthanas
@ChrisAthanas 3 жыл бұрын
The best explanation of a tricky subject that I've ever seen
@wintorez
@wintorez 3 жыл бұрын
Thank you! This video saved me in a job interview today!
@mattunlu8916
@mattunlu8916 3 жыл бұрын
I like the way how you explain things in short time!
@NFSprostreet98
@NFSprostreet98 3 жыл бұрын
THIS IS THE BEST EXPLANATION FOR CLOSURE EVER! I WISHED THIS VIDEO WAS UPLOADED A FEW MONTHS AGO WHEN I WAS INTERVIEWING!!!! DAMNNNN
@aspire.studios
@aspire.studios 3 жыл бұрын
Even though I know enough js, I would love to watch an entire js series about every important concept just like this one.
@cyrilogoh6171
@cyrilogoh6171 3 жыл бұрын
Finally understand how var and let work
@chigozie_jesse
@chigozie_jesse 2 жыл бұрын
I got asked this question in my interview today. I am happy i finally got some closure
@hamdihadjkhlifa
@hamdihadjkhlifa 3 жыл бұрын
I think if you r a teacher,your class don't need hours To understand anything, best channel
@IllIl
@IllIl 3 жыл бұрын
That was quick! Thanks, man!
@danielzaiser
@danielzaiser 3 жыл бұрын
explaining your thought process is very good advice in general
@svs6666
@svs6666 2 жыл бұрын
Happy to see you achieve your childhood dream of 1 million subs. Your explanations are so succinct.
@eyeofthetiger7
@eyeofthetiger7 3 жыл бұрын
I was literally just reading about Javascript closures this morning for an optimization problem at work and then you post this
@clebhosh
@clebhosh 2 жыл бұрын
i have never subscribed but watch your content. i just subscribed. you Sir are a brilliant mind
@talhaibnemahmud
@talhaibnemahmud 3 жыл бұрын
You deserve way more than a million subscribers ❤️
@JominJose
@JominJose 10 ай бұрын
This is the best video on closure
@RobertWildling
@RobertWildling 3 жыл бұрын
Aside from the fascinating way you can explain I am always amazed and amused by the images/videos to use! :-D
@qzbnyv
@qzbnyv 2 жыл бұрын
Jake Archibald and Surma do a great job of covering these subtleties of the scoping of for loops in one of their relatively recent HTTP 203 KZbin videos / podcasts. Strong recommend.
@muthukumar8009
@muthukumar8009 3 жыл бұрын
Probably the best explanation ever for closure
@leoingson
@leoingson 3 жыл бұрын
Yeah. But still I miss what it's actually good for. There is some form of protection for the inner function, but so what, why not just take arguments? Is it a workaround for incomplete language design of JS?
@jb5631
@jb5631 2 жыл бұрын
@@leoingson memory / performance efficiency
@precumming
@precumming 3 жыл бұрын
4:13 well, the event loop means that even if there was no delay it would still always run after i is 3. It's not a case of run it a million times and one won't be 3,3,3 due to timing, always 3,3,3. (also event loop in 100 seconds would help out a lot of people, understanding it solves a bunch of problems and I've seen people write in validations which would only fail if the event loop wasn't as it is)
@posivibez2094
@posivibez2094 2 жыл бұрын
excellent explanation thank you! was so confused before
@whysoasync4933
@whysoasync4933 3 жыл бұрын
This is the best channel on youtube!
@nterior9245
@nterior9245 3 жыл бұрын
Thanks man, learned a lot!
@currymagc
@currymagc 3 жыл бұрын
The heap is also for reference types, like objects and arrays, even in pure functions, but I suppose for this video that would be...out of scope 🤪
@theshermantanker7043
@theshermantanker7043 2 жыл бұрын
Pffft
@Paul-wy6tn
@Paul-wy6tn Жыл бұрын
yeah are primitives not stored in the stack in JS?
@milindsharma7184
@milindsharma7184 3 жыл бұрын
My god !! In my 4 year experience it was first time I intentionally used closures. And the same day this video came out. Lucky day
@ChaoticNeutralMatt
@ChaoticNeutralMatt 3 жыл бұрын
Curious what you used it for
@milindsharma7184
@milindsharma7184 3 жыл бұрын
@@ChaoticNeutralMatt In simple words, I was trying to avoid infinite dependency loop in react useCallback hook
@carloseduardomagalhaespere5112
@carloseduardomagalhaespere5112 Жыл бұрын
awesome explanation as always!
@ALXG
@ALXG 3 жыл бұрын
Fireship you are awesome 👏 (as always)
@pemessh
@pemessh 2 жыл бұрын
I needed this. Thank you
@samisbgh6253
@samisbgh6253 3 жыл бұрын
Styled-Components in 100s 🔥🔥
@peeveBR
@peeveBR 2 жыл бұрын
great video, nice and easy to understand. definitely earned a sub
@lirydasmaz9595
@lirydasmaz9595 2 жыл бұрын
I'm pretty sure you will go beyond 1 million subscribers... no doubt.
@stith_pragya
@stith_pragya 5 ай бұрын
Thank You So Much for this wonderful video............🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻
@Brunoenribeiro
@Brunoenribeiro 3 жыл бұрын
beautiful explanation
@palachokrab5711
@palachokrab5711 3 жыл бұрын
Beautifull.. you worth 1 million subscribe
@TechdubberStudios
@TechdubberStudios 3 жыл бұрын
believe it or not, I guessed that it will console log 3 for three times. But I didn't know that the behavior will change when using "let" instead of "var". There's always something new to learn, I guess.
@subhashgn1775
@subhashgn1775 2 жыл бұрын
Very well explained man.👌👏👏👏👏👏
@fatgolem69
@fatgolem69 3 жыл бұрын
700k Subs Let's Goooo Fireship
@dfla5472
@dfla5472 3 жыл бұрын
Nice! Want more videos like this.
@suyashlawand4268
@suyashlawand4268 3 жыл бұрын
You are legend🔥❤
@arhabersham
@arhabersham 2 жыл бұрын
Amazing explanation ❤️
@bhaswarkashyap3069
@bhaswarkashyap3069 2 жыл бұрын
I got this exact question today in an interview and guess what I failed miserably :(. Thanks Fireship for enhancing my storage of knowledge :)
@michaelxing3826
@michaelxing3826 3 жыл бұрын
this is a great video !
@ahmedmohmed6407
@ahmedmohmed6407 Жыл бұрын
Great Video !!
@macot79
@macot79 3 жыл бұрын
Fantastic video!
@unstable_diffusion
@unstable_diffusion 2 жыл бұрын
Subscribed. Your content is awesome
@lelilimon
@lelilimon 2 ай бұрын
2:02 it's 2024 and almost 3M subscribers. That equals to childhood dream fulfilled three times, congrats!
@im-singh
@im-singh 3 жыл бұрын
This what I subscribe without thinking 👍
@PabloGnesutta
@PabloGnesutta 2 жыл бұрын
Another way of solving the for loop problem without using let, but taking advantage of closures: for (var i = 0; i < 5; i++) { const log = (i) => { console.log(i) } setTimeout(log(i), 100); } when passing the i parameter to the log function expression, it gets encapsulated and preserve it's value even after the timeout stops... the log function will encapsulate the sate within the for loop. of course in this case it is much better to use Let, since that avoids polluting the global space, but this example is an illustration of the power of closures
@johncerpa3782
@johncerpa3782 3 жыл бұрын
Great video!
@Stoney_Eagle
@Stoney_Eagle 3 жыл бұрын
I just use let and const, saved me lots of headaches when I started learning.
@devanshsinghparmar
@devanshsinghparmar 3 жыл бұрын
He Deserve, trillions of subs
@nachiketjoshi3878
@nachiketjoshi3878 3 жыл бұрын
Best explanation.
@melvinyit6859
@melvinyit6859 3 жыл бұрын
I know is a beginner question but can you do 100 second and beyond on js callback? Thanks for all your high quality video.
@pratheeks
@pratheeks 3 жыл бұрын
2:09 I literally cried laughing
@LuXxenatorX
@LuXxenatorX 2 жыл бұрын
weirdo
@pulkitbanta7374
@pulkitbanta7374 3 жыл бұрын
Which extension are you using for the console output in vscode right next to the line? PS: I love your content.
@LucaFang
@LucaFang 3 жыл бұрын
Wow, now I know what a closure really is. Thanks my man. You’re the best :)
@esc120
@esc120 3 жыл бұрын
And before 'let' was introduced, people had to use IIFE with 'i' as parameter to make it local.
@mariansoltan1318
@mariansoltan1318 3 жыл бұрын
Make more of these, awesome.
@justingolden21
@justingolden21 3 жыл бұрын
Just wanted to say awesome logo/icon/pfp
@daniels.espitia9492
@daniels.espitia9492 Жыл бұрын
Hey Fireship! Great video, What's the extension you're using to console.log the values within the IDE next to the console.log statement?
@seal0118
@seal0118 2 жыл бұрын
impressive, very nice lets see paul allen's closure
@lesterdelacruz5088
@lesterdelacruz5088 Ай бұрын
Depends on how fast that code is processed. When the first timeout executes it's theoretically possible the for loop to still be executing.
@imanhosseini6908
@imanhosseini6908 Жыл бұрын
OrganicChemistryTutor of programming u great ser
@logichog4181
@logichog4181 3 жыл бұрын
thanks for another one
@AruljothySundramoorthy
@AruljothySundramoorthy 3 жыл бұрын
Awesome 🧡
@sujaigorai7752
@sujaigorai7752 3 жыл бұрын
Whenever an execution context is created a new scope is created...and when a function is declared inside the execution context the function hold the reference to that scope....but if no function is declared inside the execution context a new scope still created but it's immediately garbage collected after the end of execution...it's very simple concept
@_parassolanki
@_parassolanki 3 жыл бұрын
Just awesome
@Nurutomo
@Nurutomo 3 жыл бұрын
I didn't know this was called closure, i usually use this :)
@ShawnRitch
@ShawnRitch 3 жыл бұрын
WOOHOO!!! Thanks, I learned something new - again :D To bad I have a great forgeter lol
DNS Explained in 100 Seconds
2:16
Fireship
Рет қаралды 199 М.
JavaScript Closures Tutorial (Explained in depth)
19:03
ColorCode
Рет қаралды 61 М.
Normal vs Smokers !! 😱😱😱
00:12
Tibo InShape
Рет қаралды 119 МЛН
Chips evolution !! 😔😔
00:23
Tibo InShape
Рет қаралды 42 МЛН
JavaScript: How It's Made
10:54
Fireship
Рет қаралды 868 М.
How to NOT Fail a Technical Interview
8:26
Fireship
Рет қаралды 1,3 МЛН
100+ Docker Concepts you Need to Know
8:28
Fireship
Рет қаралды 775 М.
Closures in JS 🔥 | Namaste JavaScript Episode 10
22:44
Akshay Saini
Рет қаралды 749 М.
What is THIS in JavaScript? in 100 seconds
6:38
Fireship
Рет қаралды 210 М.
Javascript interview | Closure
11:44
Hitesh Choudhary
Рет қаралды 34 М.
10 regrets of experienced programmers
8:16
Fireship
Рет қаралды 974 М.
Nvidia CUDA in 100 Seconds
3:13
Fireship
Рет қаралды 1 МЛН
How much charging is in your phone right now? 📱➡️ 🔋VS 🪫
0:11
How charged your battery?
0:14
V.A. show / Магика
Рет қаралды 2,8 МЛН
Топ-3 суперкрутых ПК из CompShop
1:00
CompShop Shorts
Рет қаралды 321 М.
📱 SAMSUNG, ЧТО С ЛИЦОМ? 🤡
0:46
Яблочный Маньяк
Рет қаралды 1,7 МЛН