What is a javascript closure? ย Here is a brief description provided by the Mozilla Developer Docs:
A closure gives you access to an outer function's scope from an inner function.
In other words, ย a closure gives you the ability to access a parent level scope from a child scope even after the parent function has been terminated.
EX:
function myGuitar(str1 = ""){
let coolGtr = `${str1}`;
return function(yearPurchased){
let today_date = new Date();
let today_year = today_date.getFullYear();
let yearsPlayed = today_year - yearPurchased;
return `My favorite guitar is a ${coolGtr} ๐ธ ๐ธ ๐ธ ๐ธ I have been playing it for about ${yearsPlayed} years now.`;
}
}
let tomCat = myGuitar("Pure Salem Tomcat");
let myTomcat = tomCat(2014);
myTomcat;
The resulting output looks like this:
'My favorite guitar is a Pure Salem Tomcat ๐ธ ๐ธ ๐ธ ๐ธ I have been playing it for about 8 years now.'
Pretty nifty!!
Comments