DEV Community

Cover image for Simple guide to closures in JavaScript 😎😎
Ashish donga
Ashish donga

Posted on

Simple guide to closures in JavaScript 😎😎

Closures are function that are bundled together with the lexical environment within which that function was declared

const outer = {} => {
let outervar = "outer";
console.log(outervar);
function inner(){
console.log(outervar,innervar);
}
return inner;
}
outer();
}
Enter fullscreen mode Exit fullscreen mode

the inner function here is a closure why because it enclose or contains the variables from this outer function since it is closure we can use this outside

let myFunc = outer();
console.log(myFunc);
Enter fullscreen mode Exit fullscreen mode

output:

outer
inner(){
console.log(outervar,innervar);
}
Enter fullscreen mode Exit fullscreen mode

use of closures

1 the for loop dilemma
2 emulating private variables in javascript
3 creation of higher order function

some advance use cases of closures

carrying - it is the pattern of functions that immediately evaluate and return other function

function compositions - function composition is the ability to create functions from another function

Top comments (0)