0

I was doing this exercise on Exercism about Closure and memoizing. After struggling for a while I decided to do something like this:

export function memoizeTransform(f) {
  let prevX = null;
  let prevY = null;
  let prevResult = null;
  const func = function(x, y) {
    if(x === prevX && y === prevY) {
      return prevResult;
    } 
    prevX = x;
    prevY = y;
    prevResult = f(x, y);
    return prevResult;
  } 
  return func;
}

And it worked.

Since the function was the only thing returned, I expected an error suggesting the variables had not been declared. However, prevX, prevY and prevResult were able to hold previous argument passed to f. The exercise did not include any documentation about this and I dont know what term should I use to Google it.

Please help me understand how this happened and suggest a proper title for this question. Also, is there any way to access such properties.

Thanks!

  • `prevX`, `prevY`, `prevResult` are all encapsulated by the closure, that the function returned can see - so they're persistent as long as that returned function exists – CertainPerformance Nov 16 '22 at 15:22

0 Answers0