-->

  • How setTimeout Uses Closures with var and let

     

    How setTimeout Uses Closures with var and let

     

     How setTimeout Uses Closures with var and let 


     
    This blog we have seen javascript  closure wtih setTimeout and  solve let and var issue wtih forloop basic and how is it work, we have already seen some Javscript,  mongodb basic, CRUD operation, connect mongodb with nodejs, read, update, delete, POST, GET API etc. we should not face any problem while making Database, collection(table) and using the data in nodejs even whenever we will make API. Read data from mongodb in nodejs



    • # What is Closure with setTimeout
    • # Solve for loop issue wtih let and var using closure concept

     

     

    What is Closure ?

     

    A closure is created when a function remember its lexical scope even when its executed outside the scope. In other terms we can say that a closure give a function access to variable from its surrounding environment. 

     

     

    Don't worry i will give you an example - Suppose that you have a backpack with your notes, pens and books etc. You leave the classroom (your outer function), but you still have access to everything in your backpack (your closures). Whenever you need to solve a problem later, you can pull out the knowledge you saved in your backpack.

     

     

    function makeAdder(x) {
      return function(y) {
        return x + y;
      };
    }
    
    const add5 = makeAdder(5);
    const add10 = makeAdder(10);
    
    console.log(add5(2)); // 7
    console.log(add10(2)); // 12
    

     

     

    Here in this code makeAdder function takes a single argument x and return a new function.

    The return function takes a single argument  and return the sum of x and y.

    add5 and add10 are closures that maintain their own separate lexical environment , holding the value of x from when they were created 

     

     

    Example : A Basic Closure

     

     

    function outerfunction() {
       const outerVariable = 'Hello, Atul';
    
    
       function innerFunction() {
         console.log(outerVariable);
       }
    
       return innerFunction() {
    }
    
    const myClosure = outerFunction();
    myClosure();        //output: 'Hello, Atul'
    
    
    
    

     


    What's Happening Here?

    # innerFunction is returned from outerFunction.

    # Even though outerFunction has finished executing, innerFunction still remembers outerVariable.

    # A function is defined inside another function.

    # The inner function "remembers" the variables of the outer function.



    How setTimeout Uses Closures:

     # Inner Function: When you pass a function to setTimeout, that function forms a closure. It "remembers" the variables and values from the scope where it was created.
     

    # Delayed Execution: setTimeout schedules the function to be executed after a specified delay. But even after the surrounding code has finished running, the inner function (callback) still has access to its original scope's variables.

     

     

    for(var i=0; i< 10; i++)
    {
        setTimeout(function(){
            console.log(i)
        })
    }
    
    

     

     

    in this code why always showing output 10, 10, 10...

    The reason the code logs 10 repeatedly is due to how closures work in JavaScript. When the setTimeout callback executes, it accesses the value of i from the surrounding scope (the loop). By the time the callbacks execute, the loop has already finished, and i is equal to 10 for all of them. 

     

     

    How setTimeout Uses Closures with var and let

     

     

     


    Explanation:

     

    # The var keyword declares i in the function scope (or global scope if not inside a function). This means all iterations of the loop share the same i variable.

    # The setTimeout function schedules the callback to execute after a certain delay, but the loop doesn't wait for the callbacks to execute—it continues running to completion.

    # By the time the callbacks from setTimeout are executed, the loop has already completed, and the value of i has reached 10.

     

     Fix: Using let


    The easiest way to fix this issue is to use the let keyword instead of var. Variables declared with let have block scope, so each iteration of the loop gets its own copy of i.

     A function is defined inside another function.

    The inner function "remembers" the variables of the outer function.

     

    for (let i = 0; i < 10; i++) {
        setTimeout(function () {
            console.log(i);
        }, 0);
    }
    
    
    

     

     

    Here, each i is scoped to its specific iteration, so the output will correctly log 0, 1, 2, ..., 9.

     

     

     

    How setTimeout Uses Closures with var and let

     

    Disclaimer



    All tutorials are for informational and educational purposes only and have been made using our own routers, servers, websites and other vulnerable free resources. we do not contain any illegal activity. We believe that ethical hacking, information security and cyber security should be familiar subjects to anyone using digital information and computers. Hacking Truth is against misuse of the information and we strongly suggest against it. Please regard the word hacking as ethical hacking or penetration testing every time this word is used. We do not promote, encourage, support or excite any illegal activity or hacking.

     

     


  • 0 comments:

    Post a Comment

    For Any Tech Updates, Hacking News, Internet, Computer, Technology and related to IT Field Articles Follow Our Blog.