Skip to content

Instantly share code, notes, and snippets.

@ljharb
Forked from getify/gist:6315505
Last active December 21, 2015 14:39
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 ljharb/6321587 to your computer and use it in GitHub Desktop.
Save ljharb/6321587 to your computer and use it in GitHub Desktop.
// because of declaration hoisting, wherever we put `filter()`, it
// will be declared for a longer lifetime than is necessary.
//
// inline function expression (or arrow function) inside the loop
// isn't the answer, because then you recreate the function over
// and over again.
function doSomething() {
var items = [], i, ret = 0;
for (i=0; i<100; i++) {
items.push(Math.random());
}
function filter(v) {
return (v < 0.5);
}
for (i=0; i<items.length; i++) {
if (!filter(items[i])) items[i] = 1;
}
for (i=0; i<items.length; i++) {
ret += items[i];
}
return ret;
}
// by using block-scoping with `let` (ES6), we make `filter()`
// exist only for when it's needed, and no longer.
//
// not only does this reduce memory footprint (theoretically),
// but it also reduces namespace collision.
//
// unfortunately, as noted, this will only work in ES6, but...
// see the next snippet.
function doSomething() {
var items = [], i, ret = 0;
for (i=0; i<100; i++) {
items.push(Math.random());
}
{
let filter = function filter(v) {
return (v < 0.5);
};
for (i=0; i<items.length; i++) {
if (!filter(items[i])) items[i] = 1;
}
}
for (i=0; i<items.length; i++) {
ret += items[i];
}
return ret;
}
// same result as previous snippet, but using the `let-er` project
// so you can use `let ( .. ) { .. }` style statements and
// `let-er` will transpile your code to either ES3 compatible
// syntax (so you can use it now, today!), or you can target
// ES6-only if you want. :)
//
// https://github.com/getify/let-er
function doSomething() {
var items = [], i, ret = 0;
for (i=0; i<100; i++) {
items.push(Math.random());
}
let (filter = function filter(v) {
return (v < 0.5);
}) {
for (i=0; i<items.length; i++) {
if (!filter(items[i])) items[i] = 1;
}
}
for (i=0; i<items.length; i++) {
ret += items[i];
}
return ret;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment