Javascript Interview 101: Closure in Js and use case.

Javascript Interview 101: Closure in Js and use case.

ยท

2 min read

๐Ÿ’ก
Concept: Closure is a function that can access to parent scope even after the parent function has closed.

To understand this concept we need to break it down in two part.

Part 1: Variable and scope.

A variable can belong to the local or global scope.

a function can also access variables defined outside and inside the function

Example 1: variable inside the function (Global variable).

function myFunction() {
    let a = 4;
    return a * a;
}

Example 2: variable outside the function (Local variable)

let a = 4;
function myFunction() {
    return a * a;
}

Global variable can be used and changed by all other scripts.

Local variable can only be used inside the function where it is defined. It is hidden from other functions and other scripting code.

๐Ÿ’ก
Variables created without declaration keyword (var, let, const) are always global, event if they are created inside a function

Part 2: Javascript nested functions.

All functions have access to the scope above them.

In fact, in JS, all functions have access to the scope above them and that function is called nested functions.

Example nested function with closure.

const UserInfo = function() {
  let name = '';
  let age = ''

  const method = {
    get:function() {
      return `Name is: ${name}, age is: ${age}`;
    },

    set: function(key,value) {
      if (key === 'name') name = value;
      else age = value;
    }
  }

  return method;
}

const UserAInfo = UserInfo();
UserAInfo.set('name', 'A');
UserAInfo.set('age', 20);
console.log(UserAInfo.get()) // Name is: A, age is: 20.

I this example we can see that inside the UserInfo function have a method object that inside method object containt two function get, set. and it use to modify the name and age variable.

The only way to modify name and age variable is thought the get and set that is closure โ‡’ a function having access to their parent scope, even after the paren funcion has closed.

ย