Everything about closure

By digging in-depth of ‘CLOSURE’ concept in JavaScript, I am always confusing with the simple things like in the code below.

How addThree aurgument value is passing as the inner function ‘add’ parameter i.e ‘inner’?
Apart from this just to know what’s the difference between “Lexical scope vs Closure”?

var addTo = function(passed){
	var add = function(inner){
		return passed + inner;
		}	
	return add;	
};
var addThree = new addTo(3);
console.log(addThree(6));// output 9
1 Like

The add() function is being returned from the addTo() function and so is the value being assigned to addThree.

addThree is therefore effectively a new name to refer to add after addTo is no longer in scope.

In this case there are no variables defined inside of add that would still be in scope due to the closure after addTo finishes running. (oops - except for the value in passed)

2 Likes

How is the value 3 being remembered?

Due to the effect of closure, the add() function that’s returned from the addTo() function retains knowledge of the passed variable that was given to the addTo() function. All functions retain knowledge of the variables from the function that created them. You might want to take a look at this reintroduction to closure for more details.

2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.