fsd icon indicating copy to clipboard operation
fsd copied to clipboard

closures notes

Open albseb511 opened this issue 4 years ago • 1 comments

  • What are closures?
  • Examples -3 different examples
  • Explain debouncing
  • Explain throttling
  • Give examples of writing debouncing and throttling with native javascript
  • Interview questions

albseb511 avatar Oct 03 '20 08:10 albseb511

@albseb511

  • Closures:

    • When the parent function is called, it creates a new set of variables and assigns values to them. The child function, which is defined within the scope of the parent function, forms a closure around these variables and "remembers" their values even after the parent function has completed execution. This can be useful for creating functions that maintain state or preserve information between calls.
  • Example:


   <!-- function parent(){ -->
       let name = 'satya';
       function child(){
           console.log(name);
       }
       return child;
   }

   let newFunc = parent();
   newFunc(); # output: satya



   <!-- function makeCounter(){ -->
       let count = 0;
       function increment(){
           count++;
           console.log(count);
       }
       return increment;
   }

   let counter = makeCounter();
   counter(); #output: 1
   counter(); #output: 2
   counter(); #output: 3


   <!-- function person(name){ -->
       let age = 0;
       function getAge(){
           return this. age;
       }function setAge(newAge){
           this.age = newAge;
       }
       function getName(){
           return name;
       }
       return {
           getName,setAge,getAge
       };
   }

  let person1 = person("satya");
   console.log(person1.getName()); #output: satya
   person1.setAge(20);
   console.log(person1.getAge()); #output: 20
  • Debouncing:

    • It is a technique that is used to delay the execution of a function. Ex: when the user tries to click a button multiple times the event will trigger multiple times that causes unnecessary calling of a function. So to prevent that we use the delay and setTimeOut() to delay the execution.
  • Throttling:

    • It is a technique that is used to limit the execution of a function for a certain no of times even though the user exceeds the limit. Throttle is a higher-order function that takes a delay and a callback function as arguments.

This is my first time answering GitHub issues. And I would like to take feedback.

satya-hash avatar Mar 29 '23 06:03 satya-hash