Understanding Javascript Closures

Understanding Javascript Closures

Every function declared in JavaScript maintains a link to its outer scope. Code inside a declared function will be able to access variables declared outside the itself.

Ex.

const addSuffix = function(suffix) {
    return function(word) { return word + suffix; };
}

const addUm = addSuffix('um');
console.log(addUm('alumin'));
console.log(addUm('vibrani'));
console.log(addUm('adamanti'));

In the above example even though suffix is never defined when we call addSuffix. The function that is returned from addSuffix addUm in this case can access it's parent scope where suffix has been defined as as 'um'. Thus everytime we call addUm it just gets suffix from it's own scope.


Share Tweet Send
0 Comments
Loading...