Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why variable value is different incase of var and let in setTimeout

While practicing javascript I came across with one doubt I am printing variable i value using var and using let keyword and both the time getting different result but unable to understand why I need some explanation for this??

with var i

<script>
(function timer(){
for(let i=0;i<=5;i++){ 

setTimeout(
function clog(){
console.log(i)

},i*1000 ); 

}
}
)();
</script>

output ::

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

while using var

<script>
(function timer(){
for(var i=0;i<=5;i++){ 

setTimeout(
function clog(){
console.log(i)

},i*1000 ); 

}
}
)();
</script>

output ::

>Solution :

It is because of globally (var) or block scoped (let) value processing of javascript.

In var, variable i is globally changing and the loop finishes before settimeout function runs, so the i becomming 6 globally and console log writes yo it as 6.

In let, for every loop iteration there is an i variable belongs only that scope and settimeout function takes it, so the even if the loop finish it’s job console log writes local varible i as 0,1,2,3,4,5.

I hope i tell myself correctly.

ref: Javascript MDN

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading