Closure Examples

Developer
Size
2,792 Kb
Views
74,888

How do I make an closure examples?

What is a closure examples? How do you make a closure examples? This script and codes were developed by Steven on 31 July 2022, Sunday.

Closure Examples Previews

Closure Examples - Script Codes HTML Codes

<!DOCTYPE html>
<html >
<head> <meta charset="UTF-8"> <title>Closure Examples</title>
</head>
<body> <script src="js/index.js"></script>
</body>
</html>

Closure Examples - Script Codes JS Codes

"use strict";
// Attempt at some practical closure example.
// Closures 'remember' variables that are in their scope on creation
// Most obvious use is for private variables.
// In each case the hugeArray cannot be accessed from outside the function.
// The other advantage in this case is to avoid re-declaring our 'huge' array on every call.
function nonClosureMultByX(num) { var hugeArray = [1, 2, 3, 4, 5]; // Every run redeclares hugeArray return hugeArray.map(function (item) { // Which is probably bad. return item * num; // Memory / Performance wise });
}
console.log("BEGIN - Non Closure");
for (var i = 1; i <= 3; i++) { console.log(nonClosureMultByX(i));
}
//----------------------
function closureExample() { var hugeArray = [1, 2, 3, 4, 5]; // Declared only when closureExample is called. return function (num) { // Return function to do the real work return hugeArray.map(function (item) { // This function has access to hugeArray return item * num; // Even after closureExample has returned. }); };
}
console.log("BEGIN - Closure");
var multiplyHugeArrayByX = closureExample(); // Becomes the returned function.
for (var i = 1; i <= 3; i++) { // Knows about hugeArray. console.log(multiplyHugeArrayByX(i));
}
//------------------------
//ES6 equiv for fun
var closureExampleES6 = function closureExampleES6() { var hugeArray = [1, 2, 3, 4, 5]; return function (num) { return hugeArray.map(function (item) { return item * num; }); }; // 5 lines to 1.
};
console.log("BEGIN - ES6");
for (var _i = 1; _i <= 3; _i++) { console.log(closureExampleES6()(_i)); // Skipped naming intermediate function
} // Unnecessarily terse :)
Closure Examples - Script Codes
Closure Examples - Script Codes
Home Page Home
Developer Steven
Username volv
Uploaded July 31, 2022
Rating 3
Size 2,792 Kb
Views 74,888
Do you need developer help for Closure Examples?

Find the perfect freelance services for your business! Fiverr's mission is to change how the world works together. Fiverr connects businesses with freelancers offering digital services in 500+ categories. Find Developer!

Steven (volv) Script Codes
Create amazing Facebook ads with AI!

Jasper is the AI Content Generator that helps you and your team break through creative blocks to create amazing, original content 10X faster. Discover all the ways the Jasper AI Content Platform can help streamline your creative workflows. Start For Free!