Store and Retrieve a Function in localStorage
Last updated: December 21, 2022.
Unlike array and objects, functions are not able to represented in JSON. You cannot therefore store a function is localStorage by converting it to a JSON-string using JSON.stringify()
and then converting it back to a function with JSON.parse()
.
Instead, you can achieve the same result by getting the body of the function in string format and its parameter names as an array (which can be JSON-stringified).
You can then pass these two bits of information into the Function
constructor object. It accepts two arguments: the parameters as a comma-separated list and then the function body as a string. It will return this information to return a new function.
To get the parameter names, you can use the get-parameter-names
library. Importing it allows you to call getParameterNames()
, which returns the names of the parameters of a function that is passed into it as an array.
The body of the function can be retrieved by call substring() on a stringified version of the function and using indexOf() and lastIndexOf() to return a substring that spans from the opening to closing curly braces of the function.
Here’s what the solution looks like when storing the function in localStorage:
<!-- Imports get-parameter-names library -->
<script src="https://cdn.jsdelivr.net/npm/get-parameter-names@0.3.0/index.min.js"></script>
<script>
function f (a, b) {
const result = a + b;
return result;
}
// Defines function to pass through localStorage
const fString = f.toString();
// Stringifies function
const body = fString.substring((fString.indexOf("{"))+1,fString.lastIndexOf("}"));
// Extracts body from stringified function
const params = getParameterNames(f);
// Gets parameters name as an array
localStorage.setItem('body', body);
// Passes body directly into localStorage
localStorage.setItem('params', JSON.stringify(params));
// Passes params array in as JSON string
</script>
And here’s how to retrieve this data from localStorage to reconstitute the function:
const body = localStorage.getItem('body');
// Gets function body string
const params = JSON.parse(localStorage.getItem('params'));
// Parses JSON params string back to proper array
const f = new Function(...params, body);
// Creates a new function from params array and body string
console.log( f(1,2) ); // 3
// Successful function call!
Related links
- get-parameter-names – npm
- How to save and retrieve images from localStorage
- Check Total, Used and Remaining Space Available in localStorage
- Check if a key exists in localStorage
- A guide to using localStorage and sessionStorage
- Using JSON in JavaScript