JavaScript Interview Question #133

What is localStorage?

Generators, Browser Storage, Security & Advanced Runtime Concepts Senior Advanced

Quick Interview Answer

localStorage is a browser storage API that stores string key-value pairs for an origin. Its data normally persists across page reloads and browser sessions until explicitly removed or cleared.

Detailed Explanation

localStorage is a browser storage API that stores string key-value pairs for an origin. Its data normally persists across page reloads and browser sessions until explicitly removed or cleared.

Because values are strings, structured data is commonly serialized with JSON.stringify and restored with JSON.parse. localStorage is synchronous and should not be used as a secure store for sensitive secrets such as authentication credentials.

Code Example

const settings = {
    theme: "dark",
    pageSize: 20
};

localStorage.setItem(
    "settings",
    JSON.stringify(settings)
);

const restored = JSON.parse(
    localStorage.getItem("settings") ?? "{}"
);

console.log(restored.theme);