Skip to content

Instantly share code, notes, and snippets.

@brodybits
Last active November 2, 2016 10:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brodybits/f519b64a4eb072527f52cd64f9fe628f to your computer and use it in GitHub Desktop.
Save brodybits/f519b64a4eb072527f52cd64f9fe628f to your computer and use it in GitHub Desktop.
A simple case for JavaScript closures
CREDIT FOR INSPIRATION:
http://www.w3schools.com/js/js_function_closures.asp
ORIGINAL PURPOSE:
This is to help address a Flow Based Programming discussion comment at:
https://groups.google.com/d/msg/flow-based-programming/SckVpqE5IZM/ldeBRp5hAwAJ
The W3 schools sample above presents an easy to understand explanation of
closures but I do not think it makes a strong enough case WHY.
I will attempt to present an improved case along with a similar sample
that should still be easy to understand.
SEQUENTIAL ID DILEMMA:
A programmer wants increasing record ID values. It should be possible to start
with an arbitrary value and it should be possible to deal with multiple kinds or
tables of records.
FIRST ATTEMPT:
var recordId = 101;
function getNextRecordId() {
return recordId++;
}
Issues:
* Extra global variable
* Risk that another piece of code may change recordId
* Need to copy, paste, and adapt this code to support a second table
SOLUTION WITH CLOSURE:
function getNextIdHelper(firstId) {
var currentId = firstId;
return function() {
return currentId++;
}
}
QUICK TEST:
let getNextId = getNextIdHelper(101);
console.log('first id: ' + getNextId());
console.log('second id: ' + getNextId());
console.log('third id: ' + getNextId());
DEMO IN BROWSER:
https://jsfiddle.net/brodybits/gje79sxv/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment