ParthianShotgun
ParthianShotgun

Reputation: 602

Why does inline destructuring as a function argument not work as expected

Let's say I have code that requires access to a state object that looks like this

const store = {
  getState: () => ({
    a: "test",
    b: 1,
    c: 23,
  })
}

And a helper function that looks like this, the rest is to illustrate the fact that the output of this will not be JUST the destructured argument I passed in.

function printState ({a, b, ...rest}) {
  console.log(a, b, rest)
}

So if I try to use inline destructuring

printState({ a, b } = store.getState())

The output of above is

"test" 1 Object {
  c: 23
}

I would have expected only a and b to be passed in, and not the rest of the object. Does anyone know why this is the case?

Upvotes: 1

Views: 1380

Answers (2)

Code Maniac
Code Maniac

Reputation: 37755

printState({ a, b } = store.getState())
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^

since it's an assignment expression which returns the right hand side value, so your this function invocation is actually evaluated something like this

function printState(_ref) {
  var a = _ref.a,
      b = _ref.b,
      rest = _objectWithoutProperties(_ref, ["a", "b"]);

  console.log(a, b, rest);
}

printState((_store$getState = store.getState(),
             a = _store$getState.a,
             b = _store$getState.b, 
             _store$getState)
);

so you actually end up with printState(store.getState())

You can paste your code here and see Babel

Upvotes: 0

Maheer Ali
Maheer Ali

Reputation: 36574

{ a, b } = store.getState() is an assignment expression and the value returned by that will always be the expression on the right hand side which is store.getState().

If you want only a and b then you can use and IIFE.

const store = {
  getState: () => ({
    a: "test",
    b: 1,
    c: 23,
  })
}
function printState ({a, b, ...rest}) {
  console.log(a, b, rest)
}

printState((({a,b}) => ({a,b}))(store.getState()))

Upvotes: 3

Related Questions