[JS] Closures

Closures is a function inside a function that relies on variables in the outside function to work.

Or more elaborated:

closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function’s scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures
function giveMeEms(pixels) {
	var baseValue = 16;
	
	function doTheMath() {
		return pixels/baseValue;
	}

	return doTheMath;

}

var smallSize = giveMeEms(12);
var mediumSize = giveMeEms(18);
var largeSize = giveMeEms(24);
var xlargeSize = giveMeEms(32);

console.log("Samll size: " + smallSize());
console.log("Medium size: " + mediumSize());
console.log("Large size: " + largeSize());
console.log("Extra Large size: " + xlargeSize());

Reference:
https://www.linkedin.com/learning/javascript-essential-training-3
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures

Leave a comment

Your email address will not be published. Required fields are marked *