amitava mozumder
amitava mozumder

Reputation: 783

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.

Upvotes: 5

Views: 1008

Answers (2)

burakarslan
burakarslan

Reputation: 334

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.

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 370659

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');

Upvotes: 18

Related Questions