Your passion to teach is awesome. We can clearly see it in your eyes you want to help others to grow rather than earning money by sharing your knowledge. ❤️
Awesome! A small quiz: "closures keep reference not the actual value" (repeat it 10 times) and guess the output of below snippet for(var i=1; i { console.log(i); i = i + 1; }, i*1000); } console.log("outside: ", i) if( i < 10 ) i = 10;
outside:6 // The for loop get executed before the setTimeout func 10 11 12 13 14 //after the for loop execution now the " i " value become 10 and the value in settimeout has the value 10 beacuse of lexical scope .
got that answer of setTimout running in loop before you printed on console. Very cool example of closures. Seriously man best playlist on JS on youtube.
@@akshaymarch7 My pleasure Sr, you know something, I'm watching you from Colombia, just for you to have an Idea how you have been spreaded your knowledge around the world, Colombia is a country where the mother tongue is Spanish, I could learn some English so know I am able to check all your videos and understand you brother, thank you so much 🏆🌹
Man...I was searching the whole internet to understand this problem from months none i could understand. And today you made me understand it in just 17 minutes hats off to u man....u are a gem
Great job Akshay, I am myself a javascript developer and love JavaScript, u really inspiring, doing a grt job not only in educating them but explaining them these tough concepts so that even kindergarten child can understand, really amazed to see your passion . God Bless you.
I always watch traversy media, web dev simplifed , dev ed and all (and i always think that no one is that good enough for javascript from india).. but you prove me wrong .. Thank you bro keep making video like this..
Interviewer asked me exactly this question, but i didn't know. But thanks to the knowlege i got from your other videos, i was able to convince them to hire me. Thank you Akshay, for everything you've done and everything you'll be doing in the future. World needs more people like you, who not only are successful themselves but also guiding others and making their journey a lot easier.
Please watch this video with UTMOST ATTENTION. Listen to each line very carefully. 🙏 Next Video: CRAZY JS Interview 🤯 - ruclips.net/video/t1nFAMws5FI/видео.html Also, do let me know will you be able to answer this question in the interview now? ✌🏽
@revking I don't have a full plan myself. 😅JavaScript is huge, very huge, very very huge. I'm very confused, what to cover and what not to. If I start covering everything then this series will become a ` while(true){ makeVideo(); } ` 😅 But I'll definitely think about important topics and try to come up with Long Term Vision and a roadmap for Namaste JavaScript. 👍 Thank you so much for your comment, brother. ❤️
@@akshaymarch7 this line If I start covering everything then this series will become a ` while(true){ makeVideo(); } ` >>> super bro :) love you :) ❤️❤️❤️❤️❤️❤️❤️
After reading many articles and watching other videos about closures & loops, I finally understand why we experience this behaviour. The key was to understand that the async function stores the reference and not the value! Thank you, and I love your style of teaching.
Things learned: 1. setTimeout stores the function in a different place and attached a timer to it, when the timer is finished it rejoins the call stack and executed. 2. Without closure the var reference gives the latest value as it does not retain the original value but rather has the reference so any update in value after timeout will be shown. 3. If we use let/const because they have block scope, every time a new copy of variable is attached, thus this can be done without closure.
@Kushagra Shrivastava All of the timers start at the same time, not one after the other. So the first logs to the console after 1 second, the second after 2 seconds, the third after 3 seconds, etc. This makes them print one second part from each other.
If we use const, you will find that his example prints 1 once, then throws an error. It is a constant and can not be changed after that, i.e. it is not a changeable “variable” in a true sense, so it is a misnomer.
i tried understanding this concept by watching it several times in this week but finally after watching it now, i hope i can say understood the 80% of concept in this video. Btw extremely Thank full to you you created content of this high notch quality.
I like the way how you added memes/gif in between... put some smile while we're concentrating to learn concepts. Thank you for making us understanding JS.
Its actaully best quotes time,tide and JavaScript wait for none.😂 now I totally understand setTimeout because of your teaching is awesome. lots of respect for you
I've completed my master's in mechanical enginnering, and after that, I planned to switch my career in the IT industry. Yesterday, I cracked the first round of interviews for the position of front-end developer. All the questions on JS were from your videos, and I can bet that the interviewer has also watched your Namaste Javascript series.
Some tough concepts well handled and it's always so fun to watch as the way you keep the viewers glued to the video. I have never used JS before but now I feel that I should start doing some programs related to it for practice. I never got the idea of craziness of viewers towards this series , now I do realize their excitement for "Namaste JS". Kudos!!
Great content bhaiya really enjoying watching this playlist . Tried this problem with a different approach and it worked :) function timer() { count=0 for(var i=1;i{ count+=1; console.log(count); },i*1000) } } timer()
Bhai ek number videos hai apke. I have not watched this full video yet, currently on 05:03 minutes. I just decided to try to take this up as a coding challenge and got the desired result. You have explained the concept of closure so damn well. More power to you man.
Bhai salute. I was asked the same question in an interview when I was a fresher. Tab answer pata nahi tha aur practice se maine let use kiya tha. Interviewer asked why use let and could it done by using var. Tab kuch basic understanding nahi tha so I couldn't answer. Watching this video to prepare for new interviews after 2 years experience in field, I instantly knew what to do when you asked how to do it using var coz I remembered your previous videos lessons. Lots of love bro. Thanks for making me fall in love with JavaScript❤❤
can anyone plz help me why the suggested solution in video of using let (a block scope variable) variable isn't working here : function z ( ) { let a = 10 ; a++ ; setTimeout( () => { console.log(`from setTimeout : ${a}`) ; }, 600); console.log(`from last console log : ${++a}`) ; } z() ; my output is : from last console log : 12 from setTimeout : 12 expected output : from last console log : 12 from setTimeout : 11
@@solowolf5304 inside setTimeout the value of a is also 12 because the time it's going to log a value, it's already updated to 12 . function inside setTimeout remembers the a's reference not value. So at a's memory the value is updated to 12. So it is printing 12.
Thank you brother 🙏. Just few days ago, this question asked by interviewer 💻. and I gave same what same answer like "It will increment variable i after some m/sec". That time she told me I was wrong. But watching your video💻, now I 💡clear everything. and also now I understand "var and let" can make such change. Thank you again 😇✌️👏
recently i have an interview with HCL and the have asked the same question .... i have answered like you ha ha ha they have very much impressed even interviewer doesn't know in-depth thanks buddy you are great ........ please continue this
on the 11th clip in a row, just trying to remember this for an interview. great content man, your energy is actually making me want to write some functions and just play with them, I have never seen easier explanations of the execution context, hoisting and closures. Kuddos man
I got so excited when I saw this because I stumbled upon this exact problem some time back while I was working on a sorting visualizer project and couldn't figure out what was wrong with my code for days. Ultimately someone advised me to use async and await but now i fully understand why that didn't work.
15:52 , One common approach to achieve this with var is by using an Immediately Invoked Function Expression (IIFE) inside the loop. Here is the code: function x() { for(var i = 1; i
I jst appeared for an interview today, and the same loop question was asked to me, coudnt answer it kyunki maine Namaste JS ka ye video nahi dekha tha. But no worries, next interview mein hum phodenge. Thanks Akshay for sharing this kind of knowedge
I need to tell you that your teaching skills are class apart. I know you have great in depth knowledge of Javascript but talking about your teaching skills separately - they are mindblowing. Also, requesting for a course on NodeJS.
You explain things in very nice and different way so that everyone can understand, watching this series continuously and enjoying and waiting for new series on React js. You are just making life easy....Keep it up man 👏👏
// In below case, close is getting called for each value of i. And for each close() called a new execution context is getting created and in execution phase of that context new callback function context is created with lexical environment, which is reffering to i with which close() was called as close(i) was immediate parent of that callback function. Above cycle goes on and on until for loop ends. function clock(){ for(var i = 1 ; i
Great explanation dude! I am myself guilty of hating javascript for a long time because I thought it was kind of stupid but now I see there is a reason behind everything.
One more way to solve that problem: function x(i) { var a = i; setTimeout(() => {console.log(a);}, a * 1000); } for (var i = 0; i < 5; i++) { x(i); } This makes the function more dynamic.
Highly appreciated man. Just a note, to solve the problem with var , you are calling function with value not a reference. Problem will remain same if you pass the reference if I. Btw thank you for efforts.
I knew the answer, when you questioned. That's because of your previous video explanation on Closures, block scope, global scope. Thank you very much Akshay.
Haha, you got me. 😅 But don't worry brother, before Event Loop there are few more fundamentals to cover. After covering them, event loop will be a cakewalk. 😎 Pehle thoda mahual banayenge, fir seekhenge. 😇
For those having dfficulty like me in understanding why each iteration creates its own closure or stores i in a separate memory space unlike var. You can think of each iteration of for-loop like a mini function almost, with new/different value of i (1,2,3,4,5) and and since let is block scoped (block scope meaning within the curly braces of each mini-function) it stores reference to i at different place (different closure made by different mini-functions). Also that, a closure closes over or captures the current scope when the callback function is passed to setTimeout.. But why does it closes over when call back function is called? Because a closure is formed when a function is created inside another function and the inner function has access to the outer function's variables and parameters.
Vinoth love >> Akshay : Finally one more thing learn from closure...with block scope example... really great... Actually i pass the video around 10min thinking like why is coming continually 6 6 6 and etc. till 5 time... but not able to answered myself .. then i watched next frame then i got it because of its referring same memory space of "i" - clear : ) ....
I personally started hating js after encountering similar issues as a fresher but now after coming across your channel i realised how much i didn't know and how beautiful js really is..tysm❤️
We could also make use of IIFEs here to create a closure. Its basically the same as creating a wrapper function and explicitly calling it as shown in the video for(var i=0; i
Aksahy, your videos are so informative and interesting that sometimes I don't like to press LIKE button just not to interrupt the flow you are teaching. Really big THUMSUP to your videos 👍. Thanks!!
Saw your video on closures yesterday and had a question on it my interview today. The interviewer seemed sure that I would flunk on that question but I calmly explained him everything with confidence. :D
Thank you Akshay for making it simple to understand. I have one doubt: You have mentioned timeout to x*1000, so why every output like 1 2 3 ... is printing after exactly 1 second even if x is incrementing?
when the settimeout was executed in the current execution, at that time the value passed to the settimeout function was 1000, 2000 and so on. so based on that value the timer is confugured in the background thread. when the variable is used to manipulate, it gives output as single value which is 1000, 2000 etc. you are not keeping reference of that variable. thats why it was printing aftet 1, 2, 3 seconds.
may be running this will clear you doubt for (var i = 1; i < 4; i++) { const r = parseFloat((Math.random()*10).toFixed(2)); const timeOut = parseInt((i + r) * 1000); console.log(i, timeOut, r); setTimeout(function () { console.log('var', i, new Date().toLocaleTimeString()) }, timeOut); }
First of all, beautiful series. Amazing work giving the in-depth knowledge of JS Concepts. Thank You very much. Question: In the block of for loop when loop variable is declared using 'let', you mentioned that in each iteration, a new copy for variable i is created. i++ executes by going to the reference of the variable and then adding 1 to it. I want to understand when the new reference is created? after i++ executes and it enters the for loop? Or when the loop body ends? Also, is there a separate instance in this case just adding to the value of i and creating a new instance with the corresponding value in that loop? Basically, I understand that in each iteration a new memory address is assigned. I don't understand when this process of creating new reference executes. 1. loop body ends, new reference created, old memory freed, i++ executes? OR 2. i++ executes, new reference created with updated value, old memory freed, loop body starts? Which of these is the correct order?
Why does it create a new copy when we are using let? In every loop iteration the variable i remains the same, it is just that its value increases and is stored at the same place. Why is setTimeout unable to access just the reference to i variable and behave the same as var? Why is there a new copy associated? I did not understand why it happens just because it is block scoped. The timeout function will always have "let i" with it since it is always present in its lexical env just like a var variable.
A well explained closure from the start till the middle and en of the lecture. I thought I understood. ....but i didn't.. it is not easy. I am tired of this closure thing. I am not going to give up.
One more Solution could be (without using "let") : function x(){ var j = 1; for(var i = 1; i { console.log(j++); },1000*i); } } x(); // Thank you for your Great explanation. Grateful
3 years of coding in JavaScript and now i know that i don't know javascript properly 😂. Thank you bro tune meri aankhe khol di🤩
"Time, tide and JS wait for none" - Want this on my T-shirt 😀
😄
Having same thoughts in my mind
Same in my mind also
abhi now .... naice
and then 'await' comes 😂
Your passion to teach is awesome. We can clearly see it in your eyes you want to help others to grow rather than earning money by sharing your knowledge. ❤️
Thank you brother ❤️
@@akshaymarch7 Love you Bro for this knowledge sharing ❤
Awesome!
A small quiz:
"closures keep reference not the actual value" (repeat it 10 times) and guess the output of below snippet
for(var i=1; i {
console.log(i);
i = i + 1;
}, i*1000);
}
console.log("outside: ", i)
if( i < 10 ) i = 10;
outside:6 // The for loop get executed before the setTimeout func
10
11
12
13
14
//after the for loop execution now the " i " value become 10 and the value in settimeout has the value 10 beacuse of lexical scope .
got that answer of setTimout running in loop before you printed on console. Very cool example of closures. Seriously man best playlist on JS on youtube.
Thanks!
Thank you so much for supporting my channel, EL PODEROSO. This means a lot. ❤️
@@akshaymarch7 My pleasure Sr, you know something, I'm watching you from Colombia, just for you to have an Idea how you have been spreaded your knowledge around the world, Colombia is a country where the mother tongue is Spanish, I could learn some English so know I am able to check all your videos and understand you brother, thank you so much 🏆🌹
Spreading*
Man...I was searching the whole internet to understand this problem from months none i could understand. And today you made me understand it in just 17 minutes hats off to u man....u are a gem
❤️
Great job Akshay, I am myself a javascript developer and love JavaScript, u really inspiring, doing a grt job not only in educating them but explaining them these tough concepts so that even kindergarten child can understand, really amazed to see your passion . God Bless you.
I always watch traversy media, web dev simplifed , dev ed and all (and i always think that no one is that good enough for javascript from india)..
but you prove me wrong .. Thank you bro keep making video like this..
Interviewer asked me exactly this question, but i didn't know.
But thanks to the knowlege i got from your other videos, i was able to convince them to hire me.
Thank you Akshay, for everything you've done and everything you'll be doing in the future.
World needs more people like you, who not only are successful themselves but also guiding others and making their journey a lot easier.
❤️
Why would you go to an interview without reading a book about the subject? All of these things are almost in every JS book.
@@merlinwarage lol
@@merlinwarage can you please recommend me a good js book
I did exact same mistake what he expected and got output as all 6.
What an amazing concept you taught.
You expressions while teaching 😍.
I am binge watching NAMASTE JAVASCRIPT and look forward to do the same next weekend also. The best JS course in the world right now.
Please watch this video with UTMOST ATTENTION. Listen to each line very carefully. 🙏
Next Video: CRAZY JS Interview 🤯 - ruclips.net/video/t1nFAMws5FI/видео.html
Also, do let me know will you be able to answer this question in the interview now? ✌🏽
@revking I don't have a full plan myself. 😅JavaScript is huge, very huge, very very huge. I'm very confused, what to cover and what not to.
If I start covering everything then this series will become a ` while(true){ makeVideo(); } ` 😅
But I'll definitely think about important topics and try to come up with Long Term Vision and a roadmap for Namaste JavaScript. 👍
Thank you so much for your comment, brother. ❤️
Akshay 'this' keyword is very confusing in js..🙄🙄
Exactly : ) finally the music is awesome.....
@@EeshaKPopDanceCovers even me also
@@akshaymarch7 this line If I start covering everything then this series will become a ` while(true){ makeVideo(); } ` >>> super bro :) love you :) ❤️❤️❤️❤️❤️❤️❤️
After reading many articles and watching other videos about closures & loops, I finally understand why we experience this behaviour. The key was to understand that the async function stores the reference and not the value! Thank you, and I love your style of teaching.
Things learned:
1. setTimeout stores the function in a different place and attached a timer to it, when the timer is finished it rejoins the call stack and executed.
2. Without closure the var reference gives the latest value as it does not retain the original value but rather has the reference so any update in value after timeout will be shown.
3. If we use let/const because they have block scope, every time a new copy of variable is attached, thus this can be done without closure.
6:57
function y(){
for(var i=1;i
@Kushagra Shrivastava All of the timers start at the same time, not one after the other. So the first logs to the console after 1 second, the second after 2 seconds, the third after 3 seconds, etc. This makes them print one second part from each other.
@@chriskatanic8080 thank you so much
If we use const, you will find that his example prints 1 once, then throws an error. It is a constant and can not be changed after that, i.e. it is not a changeable “variable” in a true sense, so it is a misnomer.
@@stephen2824 ya true
This is most literally the most simplified explanation on closure and this question over the internet. As usual just amazing and thanks a ton, man
Every time you smile, I smile..that too while learning javascript😂. What a great teacher❤
Bhaiya ye video dekhne k baad jiski job lagegi vo itna kush ni hoga jitna aap thumbnail mein hore 😅. ❤️
Your namaste javascript series is like web series. I know all JS concept still i am watching your video. it's really fun. keep on #JS#GURU
You're a champ!
i tried understanding this concept by watching it several times in this week but finally after watching it now, i hope i can say understood the 80% of concept in this video. Btw extremely Thank full to you you created content of this high notch quality.
I like the way how you added memes/gif in between... put some smile while we're concentrating to learn concepts. Thank you for making us understanding JS.
Its actaully best quotes time,tide and JavaScript wait for none.😂 now I totally understand setTimeout because of your teaching is awesome. lots of respect for you
I've completed my master's in mechanical enginnering, and after that, I planned to switch my career in the IT industry.
Yesterday, I cracked the first round of interviews for the position of front-end developer.
All the questions on JS were from your videos, and I can bet that the interviewer has also watched your Namaste Javascript series.
What's the update?
Have you joined?
@@manojpatil2457 I'll join from 6th September. I've cleared one more interview for the position of a front-end developer. Thanks to Akshay once again.
@@farazhusain925
Wonderful .
Which portal you are using for applying?
is react also asked in that
@@ritikraj2629 Yes
I will remember closures for ever, yeahhhhh!!!!! 🏆🏆❤️❤️❤️❤️❤️❤️❤️❤️❤️
Some tough concepts well handled and it's always so fun to watch as the way you keep the viewers glued to the video. I have never used JS before but now I feel that I should start doing some programs related to it for practice. I never got the idea of craziness of viewers towards this series , now I do realize their excitement for "Namaste JS". Kudos!!
Great content bhaiya really enjoying watching this playlist . Tried this problem with a different approach and it worked :)
function timer()
{
count=0
for(var i=1;i{
count+=1;
console.log(count);
},i*1000)
}
}
timer()
Bhai ek number videos hai apke. I have not watched this full video yet, currently on 05:03 minutes. I just decided to try to take this up as a coding challenge and got the desired result. You have explained the concept of closure so damn well. More power to you man.
Bhai salute. I was asked the same question in an interview when I was a fresher. Tab answer pata nahi tha aur practice se maine let use kiya tha. Interviewer asked why use let and could it done by using var. Tab kuch basic understanding nahi tha so I couldn't answer. Watching this video to prepare for new interviews after 2 years experience in field, I instantly knew what to do when you asked how to do it using var coz I remembered your previous videos lessons. Lots of love bro. Thanks for making me fall in love with JavaScript❤❤
Do note that the timer can expire before the whole loop gets executed when you change the stopping condition from i
can anyone plz help me why the suggested solution in video of using let (a block scope variable) variable isn't working here :
function z ( ) {
let a = 10 ;
a++ ;
setTimeout( () => {
console.log(`from setTimeout : ${a}`) ;
}, 600);
console.log(`from last console log : ${++a}`) ;
}
z() ;
my output is :
from last console log : 12
from setTimeout : 12
expected output :
from last console log : 12
from setTimeout : 11
@@solowolf5304 function z ( ) {
let a = 10 ;
a++ ;
function local(x) {
setTimeout( () => {
console.log(`from setTimeout : ${x}`) ;
}, 600);
}
local(a)
console.log(`from last console log : ${++a}`) ;
}
z() ;
@@solowolf5304 function z ( ) {
let a = 10 ;
let b = a++ ;
b++
setTimeout( () => {
console.log(`from setTimeout : ${b}`) ;
}, 600);
console.log(`from last console log : ${++a}`) ;
}
z()
@@solowolf5304 please carefully look for....++I and I++ .
@@solowolf5304 inside setTimeout the value of a is also 12 because the time it's going to log a value, it's already updated to 12 . function inside setTimeout remembers the a's reference not value. So at a's memory the value is updated to 12. So it is printing 12.
Thank you brother 🙏. Just few days ago, this question asked by interviewer 💻. and I gave same what same answer like "It will increment variable i after some m/sec". That time she told me I was wrong. But watching your video💻, now I 💡clear everything. and also now I understand "var and let" can make such change. Thank you again 😇✌️👏
Sir, Please make series on React as well. Will be highly appreciated :)
Yes React please
And also make it relative with namaste js series.
Yes we need a series on react just like this it will be very helpful
Exactly. akashay bro. Waiting for it.
yes we need "Howdy React!" :P
I was asked this question at an interview with DeliveryHero. Brilliant!
Great man, did you crack the job? How many rounds of interviews did you go through and what were those rounds?
This is the kind of teacher I have been waiting all life.
recently i have an interview with HCL and the have asked the same question .... i have answered like you ha ha ha they have very much impressed even interviewer doesn't know in-depth thanks buddy you are great ........ please continue this
6:10 😂 SAVAGE 🔥
"That's how it is not.."
Haha 😂
on the 11th clip in a row, just trying to remember this for an interview. great content man, your energy is actually making me want to write some functions and just play with them, I have never seen easier explanations of the execution context, hoisting and closures. Kuddos man
hey , did you clear the interview ? was the questions asked were covered in this playlist ?
i think he is dead....he might have committed sucide bcoz he is not replying
@@CharanGs-t4i
I always thought that only C++ template spaghetti has something mind bending to offer, but now I have a purpose to learn JS. Thank you Akshay bhai!
The whole Namaste JS series feels like dope and the meme at the end of this video just mimics that!!! Hats off to you Akshay.
Amazing bro.. I have been working with JS for 4 years.. Finally I understood what closure was. Thank you
Not yet, next video will cover more about closures. 🔥
Javascript is tricky but your explanation is so crisp and clear that even a non JS developer can understand it.
I got so excited when I saw this because I stumbled upon this exact problem some time back while I was working on a sorting visualizer project and couldn't figure out what was wrong with my code for days. Ultimately someone advised me to use async and await but now i fully understand why that didn't work.
The problem with Akshay is that, He has positive radiating energy. You can't stop watching his videos :D
I wish everyone has this problem :)
I have never laughed at a tutorial till now! Keep the humor up in your videos brother!
Akshay, lovely explanation, awesome outro music. Now Liggi is going to be on a loop today. 😂
after watching namste JS i am in love with JS, and "time tide and JS waits for none " it was actually a good joke and nice Quote by you .
15:52 , One common approach to achieve this with var is by using an Immediately Invoked Function Expression (IIFE) inside the loop.
Here is the code:
function x() {
for(var i = 1; i
Ya this is iife making allocating a new memory space each time the loop iterates
I jst appeared for an interview today, and the same loop question was asked to me, coudnt answer it kyunki maine Namaste JS ka ye video nahi dekha tha. But no worries, next interview mein hum phodenge. Thanks Akshay for sharing this kind of knowedge
Finally I found 1 channel which sales diamond's and it is free.
I need to tell you that your teaching skills are class apart. I know you have great in depth knowledge of Javascript but talking about your teaching skills separately - they are mindblowing. Also, requesting for a course on NodeJS.
You explain things in very nice and different way so that everyone can understand, watching this series continuously and enjoying and waiting for new series on React js. You are just making life easy....Keep it up man 👏👏
Never ever learnt such topics man . This teacher is on a different level.
// In below case, close is getting called for each value of i. And for each close() called a new execution context is getting created and in execution phase of that context new callback function context is created with lexical environment, which is reffering to i with which close() was called as close(i) was immediate parent of that callback function. Above cycle goes on and on until for loop ends.
function clock(){
for(var i = 1 ; i
you saved my day my man. what a wonderful explaination. you dived right back to the basics..thanks!!
Great explanation dude! I am myself guilty of hating javascript for a long time because I thought it was kind of stupid but now I see there is a reason behind everything.
One more way to solve that problem:
function x(i) {
var a = i;
setTimeout(() => {console.log(a);}, a * 1000);
}
for (var i = 0; i < 5; i++) {
x(i);
}
This makes the function more dynamic.
You are a great man 🎉
you dont need var a there..
This syntax also will create closure :) thanks for great videos.
setTimeout(
(i) => {
console.log(i);
},
1000 * i,
i
);
To be simple,
Let is block scoped and also function scoped,
But var is function scoped not block scoped
Highly appreciated man. Just a note, to solve the problem with var , you are calling function with value not a reference. Problem will remain same if you pass the reference if I. Btw thank you for efforts.
I knew the answer, when you questioned. That's because of your previous video explanation on Closures, block scope, global scope.
Thank you very much Akshay.
Best JavaScript tutorial video I have ever watched !!
"Many senior engineers will pull their hair over this". Well, if you don't know about the asynchronous nature of Javascript, you aren't senior!
Exactly
This isn't async nature of js dude
wastage of time
You're GOD of Javascript, Akshay...
Superb explanation
Yes bro crt, many interviewer asked this question
Most underrated mentor out there..... 🔥🔥🔥
Akshay explains confusing stuff: "You will pull your hair"
Baldie me: give me something else, I don't wanna play
I think you still got some hairs, dig deeper🌝
@@UMBERELLA_ACADEMY 😂😂😂😂😂😂😂😂😂😂😂😂😂😂😂😂😂😂😂😂😂😂😂😂😂😂😂😂
Hey Akshay!! Loving your videos. Thanks bro!!
Now that you spoke of event loop, we need a video on this topic too 😀
Folks, like this comment if you too want a video on event loop.
Thanks!! 🙏
Haha, you got me. 😅
But don't worry brother, before Event Loop there are few more fundamentals to cover. After covering them, event loop will be a cakewalk. 😎
Pehle thoda mahual banayenge, fir seekhenge. 😇
Event Loops can be understood by JSConf webinars .
Hey folks, event loop video is out on this channel 3 days ago, check it out.
@@akshaymarch7 isi bat pe hindi me bhi bana do 🤩🤩
@@lsd3284 true.
This is the best Javascript playlist in the entire universe!
For those having dfficulty like me in understanding why each iteration creates its own closure or stores i in a separate memory space unlike var.
You can think of each iteration of for-loop like a mini function almost, with new/different value of i (1,2,3,4,5) and and since let is block scoped (block scope meaning within the curly braces of each mini-function) it stores reference to i at different place (different closure made by different mini-functions).
Also that,
a closure closes over or captures the current scope when the callback function is passed to setTimeout.. But why does it closes over when call back function is called?
Because a closure is formed when a function is created inside another function and the inner function has access to the outer function's variables and parameters.
thankyou I was able to understand the concept but your view made my concept more clear
I was already aware of the question and output but didn't know how to fix this problem. You explained it very beautifully
"Wherever I go, I see him" - Closures
Vinoth love >> Akshay :
Finally one more thing learn from closure...with block scope example... really great...
Actually i pass the video around 10min thinking like why is coming continually
6
6
6 and etc. till 5 time... but not able to answered myself .. then i watched next frame then i got it because of its referring same memory space of "i" - clear : ) ....
Not many senior developer are not pulling their hairs because they don't have
😂
I personally started hating js after encountering similar issues as a fresher but now after coming across your channel i realised how much i didn't know and how beautiful js really is..tysm❤️
Cheers ❤️
6:26 panic sets in. 😭
11:07 relief. 😊
This shows how patiently you watched the video, brother! ❤️
Very very interesting explanation, thank you Akshay sir for creating this!
You're the hope for JavaScript Developers!! 💯
Oh my god!
I had an interview today and the interviewer asked this. The first question in JS he asked was this.
But I didn't know it. 😐
Next time, aag laga dena mere dost!! 🔥
I've an interview scheduled today yet I'm watching this playlist, my confidence is getting higher with completing every video
We could also make use of IIFEs here to create a closure. Its basically the same as creating a wrapper function and explicitly calling it as shown in the video
for(var i=0; i
wow....great
Was working on DrumKit Project as a newbie to JS got frustrated when I got stuck in the "for loop". Thanks a lot for explaining.
Learning: never use var in js, unless almost necessary
Var will mess your code beyond recognition
very true!
Aksahy, your videos are so informative and interesting that sometimes I don't like to press LIKE button just not to interrupt the flow you are teaching. Really big THUMSUP to your videos 👍. Thanks!!
4 solutions to this question
1. Use let instead of var
2.use iife
3.Bind the callback function with the value ofi
4.move i to outer function with let
U mean 2 poin variable life time' u saying right
Saw your video on closures yesterday and had a question on it my interview today. The interviewer seemed sure that I would flunk on that question but I calmly explained him everything with confidence. :D
Thank you Akshay for making it simple to understand. I have one doubt: You have mentioned timeout to x*1000, so why every output like 1 2 3 ... is printing after exactly 1 second even if x is incrementing?
when the settimeout was executed in the current execution, at that time the value passed to the settimeout function was 1000, 2000 and so on. so based on that value the timer is confugured in the background thread. when the variable is used to manipulate, it gives output as single value which is 1000, 2000 etc. you are not keeping reference of that variable. thats why it was printing aftet 1, 2, 3 seconds.
Because, Only the inner function part is put somewhere else not the whole setTimeout function.
Akshay sir, please correct me if i am wrong.
may be running this will clear you doubt
for (var i = 1; i < 4; i++) {
const r = parseFloat((Math.random()*10).toFixed(2));
const timeOut = parseInt((i + r) * 1000);
console.log(i, timeOut, r);
setTimeout(function () {
console.log('var', i, new Date().toLocaleTimeString())
}, timeOut);
}
Thanks again this question asked me in interview today and i explained it pretty well. You are awesome !!!! Keep creating such videos
my interviewer asked the same & that time i was stuck on it.
thanks for making me understand 😍
First of all, beautiful series. Amazing work giving the in-depth knowledge of JS Concepts. Thank You very much.
Question: In the block of for loop when loop variable is declared using 'let', you mentioned that in each iteration, a new copy for variable i is created.
i++ executes by going to the reference of the variable and then adding 1 to it.
I want to understand when the new reference is created? after i++ executes and it enters the for loop? Or when the loop body ends?
Also, is there a separate instance in this case just adding to the value of i and creating a new instance with the corresponding value in that loop?
Basically, I understand that in each iteration a new memory address is assigned. I don't understand when this process of creating new reference executes.
1. loop body ends, new reference created, old memory freed, i++ executes?
OR
2. i++ executes, new reference created with updated value, old memory freed, loop body starts?
Which of these is the correct order?
6:10 the time i watched for 4-5 times looks like you got my mind what i was thinking
Why does it create a new copy when we are using let? In every loop iteration the variable i remains the same, it is just that its value increases and is stored at the same place. Why is setTimeout unable to access just the reference to i variable and behave the same as var? Why is there a new copy associated?
I did not understand why it happens just because it is block scoped. The timeout function will always have "let i" with it since it is always present in its lexical env just like a var variable.
Me too he just said block scoped but he didn't explain how it's new variable not even in his block scope video. If you know can you explain?
@@jasonbrody4618 I too dont understand. Can Anyone explain this.?
1 question -
I used let j=i inside loop just above the setTimeout
And used console.log(j) inside setTimeout and its worked...
You made me pull my hair so many time, I am bald now. What to do? :p
🥺 Don't worry brother, this will help you - amzn.to/2VUgHAu
@@akshaymarch7 😂😂
@@akshaymarch7 😂😂😂
@@akshaymarch7 grt sir this solution will enclose his baldness.
kudos to you
this is heavy content but with your explanation its become easy .
great video
A well explained closure from the start till the middle and en of the lecture. I thought I understood. ....but i didn't.. it is not easy. I am tired of this closure thing. I am not going to give up.
This is Beauty of Javascript we predict something but it comes deifferent !
Brother you explain each and every complex topics with ease.👍👍👍👍👀👀👀 thanks..
I will gift you a t-shirt with the quote "time , tide and js waits for none " once I get a job ,
I am really greattful for this awesome course.
One more Solution could be (without using "let") :
function x(){
var j = 1;
for(var i = 1; i {
console.log(j++);
},1000*i);
}
}
x();
// Thank you for your Great explanation. Grateful
javascript seems so cool and easy now with your explaination, and your smile at last make me smile too :)
Thanks Akshay
my Interviewer asked 3 qns from it iam unable to anser now got clarity thanks