Search code examples
ecmascript-6ecmascript-harmony

ES2015 Destructure object twice in same scope


Is there a clean way to destructure the same variables from 2 similar objects in the same scope?

function(oldState, newState) {
  let {foo, bar} = oldState;
  // do stuff //
  let {foo, bar} = newState; // illegal double declaration in same scope
  {foo, bar} = newState; // illegal, not sure why
  let {foo: foo1, bar: bar1} = newState; // legal but ugly
  foo = newState.foo; // legal, but requires multiple lines
}

Solution

  • You can wrap the assignment in parens to reassign the variables via destructuring. The reason this is necessary is because otherwise the { is assumed by the parser to begin a block rather than an object literal or assignment pattern. This blog post explains the situation in more detail.

    function(oldState, newState) {
      let {foo, bar} = oldState;
      // do stuff //
      ({foo, bar} = newState);
    }