Answers for "How Closure works totally different in Loop!!!!"

0

How Closure works totally different in Loop!!!!

Explanation From Medium: 

//https://medium.com/brandsoft/variable-scope-and-iifes-in-javascript-3cf85f79597e#:~:text=By%20using%20an%20IIFE%2C%20we,when%20the%20IIFE%20is%20executed.

Code:

// for (var i = 0; i<=5; i++){  // this type of problem created
//     setTimeout(function (){
//         console.log('Current Value is ' + i); 
//     }, 1000 * i)
// }

// for (var i = 0; i <= 5; i++) {
//     (function (n) { // to avoid previous example's fault
//         setTimeout(function () {
//             console.log('Current Value is ' + n);
//         }, 1000 * n)
//     })(i);
// }

// for (let i = 0; i<=5; i++){ // in this case (let) behaves different from var
//     setTimeout(function (){
//         console.log(i);
//     }, 1000 * i)
// }
Posted by: Guest on January-11-2021

Code answers related to "How Closure works totally different in Loop!!!!"

Code answers related to "Javascript"

Browse Popular Code Answers by Language