What are Closures in Javascript?


Posted On: Feb 22, 2018


Closures are nothing but a statefull functions.

A closure is an inner function that has access to outer function’s variables in addition to it’s own variable and global variables.In simple term a closure is a function inside a function.Closures using Lexical scoping in which function have access to global and outer variables.Below is a sample example of Javascript closure.

function employee() {
    var employee_dept = 'IT';
    return {
        getDept: function ()  {           
          return employee_dept;
        setDept: function (new_dept)  {
            employee_dept = new_name;

var emp1 = employee (); // In this juncture, the employee_dept outer function has returned.​
mjID.getDept(); // IT
mjID.setDept('Account'); // Changes the outer function's variable​
mjID.getDept(); //outputs Account

Closures prevents your important variable to be modified accidently.It can be only modified by itself.

    Related Questions

    Please Login or Register to leave a response.

    Related Questions

    Typescript Interview Questions

    What is Typescript?

    Typescript is a free and open-source programming language which is designed and developed by Microsoft. It was designed ..

    Typescript Interview Questions

    List some features of Typescript?

    Features of Typescript are:- Typescript can be compiled to all major versions of Javascript(ES3,ES5,ES6,ES7). Typescrip..

    Typescript Interview Questions

    List some benefits of using Typescript?

    Following are some benefits of using Typescript One of the biggest advantages of Typescript is its code completion and ..