Skip to main content

Posts

Showing posts with the label var

understanding the difference between var and let in javascript

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