-1

I've tried searching for an answer for this but I think I am missing something, tried searching for "call function in variable" without any luck. (Any tips on what I should've searched for are also welcomed!)

Anyways, I would like some clarification of how the code below works!

function createStore() {
  let state = []
    
  const getState = () => state
    
  const dispatch = (action) => {
    state = state.concat([action])
  }
    
  return {
    getState,
    dispatch
  }
}

const store = createStore()

store.dispatch(1)
store.dispatch(2)

So, if i run store.dispatch(1) and then again store.dispatch(2) as above and then run store.getState, I get an array of [1, 2].

What I don't really understand is how these dispatches are stored?

I understand that they are saved within the state variable of the function, but shouldn't the function reset itself after being called?

It must be a local scope and only accessible via the function?

Are there any other way of accessing the state without calling getState?

Still learning JavaScript, so any clarification on this would be super!

isherwood
  • 58,414
  • 16
  • 114
  • 157
  • Does this answer your question? [How do JavaScript closures work?](https://stackoverflow.com/questions/111102/how-do-javascript-closures-work) – Aplet123 Dec 28 '20 at 14:27

1 Answers1

0

I understand that they are saved within the state variable of the function, but shouldn't the function reset itself after being called?

The getState and dispatch functions hold a reference to (technical term, "close over") the state variable — and after createStore returns, it isn't in scope for access any other way. The only thing that could "reset" it is calling createStore again, but if you do that it creates a new instance of state for that call, and returns new instances of getState and dispatch closing over the new state, all independent of the old ones. This is how lexical closure works.

hobbs
  • 223,387
  • 19
  • 210
  • 288