Protected Complex Assignments

Assignments where temporary variables are required - an elegant way to scope the temporary variables.

by nemesarial

Babel + JSX

/******************************************************************** /
  Protected Complex Assignments
  -----------------------------
  A pattern to provide an elegant way of scoping temporary variables
  that are used in the production of a variable that is actually 
  required.
/********************************************************************/

// This version is the most flexible as it will let you return a 
// variable rather than modifying an existing variable. 
// Could therefore also be used as an expression.
const someVar = (() => { let a = 1; let b = 2; return a + b; })();

// The second method is a little less flexible, and will let you 
// modify an existing variable only. It is, in my opinion, more 
// elegant and easier to read.
let someOtherVar; { let a = 1; let b = 2; someOtherVar = a + b; }

// Even a more complex multi-line operation reads easily:
let fib100; { // Store the f(100) for fibonacci sequence.
  fib100=0;
  let num=100, a=1, temp;
  while (num >= 0){
    temp = a;
    a = a + fib100;
    fib100 = temp;
    num--;
  }
}