Skip to content

Instantly share code, notes, and snippets.

@getify

getify/gist:6315505

Last active Dec 21, 2015
Embed
What would you like to do?
exploring let with function expressions
// 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 filter(v) {
return (v < 0.5);
}
function doSomething() {
var items = [], i, ret = 0;
for (i=0; i<100; i++) {
items.push(Math.random());
}
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