Skip to content

Instantly share code, notes, and snippets.

@user24
Created November 7, 2014 11:08
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 user24/14908e7fbce0349863be to your computer and use it in GitHub Desktop.
Save user24/14908e7fbce0349863be to your computer and use it in GitHub Desktop.
// It would be very simple to write this function to sort-of mimic let;
lett({
'blockScopeVar': 4
}, function (blockScopeVar) {
//blockScopeVar === 4 // true
});
// Then when you want to change the code to actually use let, it's fairly easy;
// just write your let declarations and rip out the callback's innards;
let blockScopeVar = 4;
//blockScopeVar === 4 // true
@user24
Copy link
Author

user24 commented Nov 7, 2014

so lett would look something like this:

function lett(vars, callback) {
var valuesArray = Object.keys(vars).map(function (varName) {
return vars[varName];
});
callback.apply(this, valuesArray);
}

@getify
Copy link

getify commented Nov 7, 2014

Why not just?

(function(blockScopeVar){
     //blockScopeVar === 4 // true
})(4);

  1. While Object.keys(..) tends to be somewhat predictable with ordering the same as you listed them, it's not at all guaranteed. So, if it listed the variables in a different order than what you put into the object literal, you'd have an ordering-mismatch with your parameters. Since it's not reliable, I don't think I'd trust it.

  2. Wrapping a function around any arbitrary code (either my style or yours) isn't necessarily as "safe" as normal blocks w/ let, because functions change the meaning of this, return, break, continue, yield, etc.

    Where { let x = 2; return y * x; } is perfectly fine and safe, lett({ x: 2 },function(x){ return y * x; }) wouldn't work. :(

  3. There are tools for transpiling let into pre-ES6 browsers. For example:

    • defs.js
    • traceur
    • let-er --> this is my project. it uses let (x = 2) { .. } style syntax, which is not standard for ES6, but I think is closer to the style you want to write anyway. let-er transpiles such code to either { let x = 2; .. } for ES6, or try { throw 2; } catch(x) { .. } for ES3.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment