Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store arguments between function calls in JS

A function is getting called multiple times is there a way to store the context/arguments of last function call and check with current ones.

like image 920
amitava mozumder Avatar asked Jul 24 '19 06:07

amitava mozumder


2 Answers

When defining the function, I'd use a closure to store a persistent variable, reassigned to the arguments passed on every call, eg:

const fn = (() => {
  let lastArgs;
  return (...args) => {
    console.log('function was called with args:', args);
    console.log('past args were:', lastArgs);
    lastArgs = args;
  };
})();

fn('foo', 'bar');
fn('baz');
like image 198
CertainPerformance Avatar answered Oct 02 '22 09:10

CertainPerformance


You can use a global variable for storing data. Everytime a new function called check new arguments with global variable and do what you want.

like image 41
burakarslan Avatar answered Oct 02 '22 09:10

burakarslan