Is it possible to pass an argument to a variable initialized using let?

113 views Asked by At

Below is the code snippet used in one of the tutorials I am learning from now. Can someone please help to understand how an argument 'mediastate' can be passed to a variable 'transientListen' in the 'notify' function?

function createMediaListener(queries) {
  let transientListener = null;

  const keys = Object.keys(queries);

  const queryLists = keys.reduce((queryLists, key) => {
    queryLists[key] = window.matchMedia(queries[key]);
    return queryLists;
  }, {});

  const mediaState = keys.reduce((state, key) => {
    state[key] = queryLists[key].matches;
    return state;
  }, {});

  const notify = () => {
    if (transientListener != null) transientListener(mediaState);
  };

  const listeners = keys.reduce((listeners, key) => {
    listeners[key] = event => {
      mediaState[key] = event.matches;
      notify();
    };

    return listeners;
  }, {});

  const listen = listener => {
    transientListener = listener;
    keys.forEach(key => {
      queryLists[key].addListener(listeners[key]);
    });
  };

  const dispose = () => {
    transientListener = null;
    keys.forEach(key => {
      queryLists[key].removeListener(listeners[key]);
    });
  };

  const getState = () => mediaState;

  return { listen, dispose, getState };
}

export default createMediaListener;
1

There are 1 answers

0
lortschi On

How I understand, the "listen" function is called by return statement in the module. The problem is, "listen" function needs a parameter, otherwise is: transientListener = listener; => undefined.