Closure in javascript

Ayesha Malik
1 min readApr 2, 2023

--

Closure is a concept in JavaScript where inner functions have access to the properties and methods of outer functions even after the execution of the external function is done.

function example() { 
let name = "john";
function displayName() {
console.log(name);
}

displayName();
}

example(); // "john"

If you notice the variable blog is declared above the function displayName(), but it can be accessed inside it.

This is because variables are lexical scope in JavaScript and can be accessed anywhere inside that scope unless and until they are overridden. In the above example, the variable is function scoped and it can be accessed anywhere within the function body (even in the inner functions).

function example() { 
let name = "john";
function displayName() {

let name = "hello";
console.log(name); // Preference is always given to
// the nearest declared one.
}

displayName();
}

example(); // "hello"

closures can access not only variables but also other properties and methods of the outer function. This makes closures powerful as even if we return the inner function, it will have access to the variables in the outer scope and perform all sorts of operations.

--

--

Ayesha Malik

I’m a full-time software engineer who loves sharing knowledge to help others become better developers.