Closure in JavaScript


a closure is the combination of a function bundled together with references to it's surrounding state(the lexical environment).In JavaScript, closures are created every time a function is created, at function creation time,a closure gives you access to an outer function’s scope from an inner function
The inner function will have access to the variables in the outer function scope

closures arte commonly used to give objects data privacy,Data privacy is an essential property that helps us program to an interface, not an implementation. This is an important concept that helps us build more robust software because implementation details are more likely to change in breaking ways than interface contracts.
In functional programming, closures are frequently used for partial application & currying. This requires some definitions:
Application: The process of applying a function to its arguments in order to produce a return value.

Partial Application: The process of applying a function to some of its arguments. The partially applied function gets returned for later use. In other words, a function that takes a function with multiple parameters and returns a function with fewer parameters. Partial application fixes (partially applies the function to) one or more arguments inside the returned function, and the returned function takes the remaining parameters as arguments in order to complete the function application.

partialApply(targetFunction: Function, ...fixedArgs: Any[]) =>  
  functionWithFewerParams(...remainingArgs: Any[])
const add = (a, b) => a + b;  
const add10 = partialApply(add, 10);  

10 becomes a fixed parameter

const partialApply = (fn, ...fixedArgs) => {  
  return function (...remainingArgs) {
    return fn.apply(this, fixedArgs.concat(remainingArgs));


Understanding hoisting will help you organize your function scope,cariable declaration and function definition are hoisted to the top.Variable definition is not.even if you declare and define a variable on the same line. Also, variable declaration is letting the system know that the variable exists while definition is assigning it a value.

function doTheThing() {  
  // ReferenceError: notDeclared is not defined

  // Outputs: undefined
  var definedLater;

  definedLater = 'I am defined!'
  // Outputs: 'I am defined!'

  // Outputs: undefined
  var definedSimulateneously = 'I am defined!'
  // Outputs: 'I am defined!'

  // Outputs: 'I did it!'

  function doSomethingElse(){
    console.log('I did it!');
  }//function definition
  // TypeError: undefined is not a function

  var functionVar = function(){
    console.log('I did it!');

declare all of your variables at the top of your function scope so it is clear which scope the variables are coming from. Define your variables before you need to use them. Define your functions at the bottom of your scope to keep them out of your way.