Skip to content

Instantly share code, notes, and snippets.

@arnorhs
Created October 14, 2011 05:24
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 arnorhs/1286313 to your computer and use it in GitHub Desktop.
Save arnorhs/1286313 to your computer and use it in GitHub Desktop.
Examples from a blog post about closures in Javascript
// This function accepts either an array or a single value and
// returns an array of the values that didn't match the string
// provided in argument #2
function y (myvar,str) {
// this variable will be returned from this function
var collection = [];
// Check if the provided variable is an array or not
if (myvar instanceof Array) {
// iterate through all elements and check if they
// match the string provided as the second argument
for (var i = 0; i < myvar.length; i++) {
if (myvar[i] != str) {
collection.push(myvar[i]);
}
}
} else {
// it's not an array, just check on the one value
if (myvar != str) {
collection.push(s);
}
cl(myvar,collection);
}
return collection;
}
// now the same function uses a closure to implement the
// functionality of checking and adding the variable to the
// returned array
function y (myvar,str) {
// define the variable we'll return and a closure that will
// determine if the string would match or not and adds it
// to the collection array if it does not
var collection = [],
cl = function (s) {
if (s != str) {
collection.push(s);
}
};
// if it's not an array, we'll just call the function on
// the single element, but if it is, we'll call it on all
// the elements of the array
if (myvar instanceof Array) {
for (var i = 0; i < myvar.length; i++) {
cl(myvar[i]);
}
} else {
cl(myvar);
}
return collection;
}
function ret (a) {
return function (somevar) {
return somevar === a;
}
}
b = ret("some string");
b("other string");
b("some string");
function ret (a) {
return function ($somevar) {
// we're assuming it's a jQuery object
return somevar.is(a);
}
}
is_hidden = ret(':hidden');
is_checked = ret(':checked');
is_hidden($('.mydiv'));
is_checked($('input.myinput'));
function all_elements_match (arr, func) {
var ret = [];
// Loop through all elements of the array and call the
// callback which will tell the function if the element
// should be added to the array or not
for (var i = 0, l = arr.length; i < l; i++) {
if (func(arr[i])) {
ret.push(arr[i]);
}
}
return ret;
}
var fruit = ["apple","orange","mango","grape","avacado"];
// return an array of all the fruit that start with the
// letter "a"
all_elements_match(fruit, function (element) {
return element.match(/^a.*/) !== null;
});
// will return ["apple", "avacado"]
// return an array of all the fruit that have more than
// 5 letters in their name
all_elements_match(fruit, function (element) {
return element.length > 5;
});
// will return ["orange","avacado"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment