Introduction Javascript has multiple ways of declaring variables in the code as given below. However each type of usage has its own context. let x = 10; const y =10; var z = 10 Problem Statement I recently came across a problem statement regarding the above type of variable declaration and usage Snippet: 1 In the below snippet, the output will be 3,3,3. The reason for this behavior is that in javascript, the variable defined as var will be referring to the address of i since it has a function scope so, whenever the value of i is incremented, the change will be reflected inside the setTimeout method as well as they are pointing to the same address for ( var i = 0 ; i < 3 ; i++) { setTimeout ( () => console . log (i), 1 ); } Snippet2 for ( let i = 0 ; i < 3 ; i++) { setTimeout ( () => console . log (i), 1 ); } In the above snippet, we have used a variable with let keyword which has a block scope, so there is a copy of i inside the setTimeout. Hence the above snippet
I have 11+ years of experience in Software development. I am proud to be in the top 5 Multi-Tenancy answerers @ Stackoverflow. I have worked with C#, Java, MySQL, SQL Server, Multi-tenancy, AWS, Azure, Terraforms, Java with Spring boot and Python, groovy, bat scripts