Discussion Javascript

Store functions in localStorage

We can only store string data to localStorage and sometimes we need to store methods and invoke later.
In order to do this, Javascript provides functionality to stringify methods.
Here is an example function.
const func = function sum(a, b) { return a + b; }
func.toString() returns a string like function sum(a, b) { return a + b; }
Now we store this string into localStorage
localStorage.setItem(‘func’, func.toString());

We can restore function like this.
const restored = new Function(localStorage.getItem(‘func’));
Now we invoke function const result = restored(3, 4);
It returns 7 as a result.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *