What is localStorage in JavaScript?

localStorage is a Web Storage API in JavaScript that allows developers to store key-value pairs in a web browser. This data persists even after the browser is closed and reopened, making it useful for saving user preferences, game scores, or any other data that needs to be retained across sessions.

localStorage is part of the larger Web Storage API, which also includes sessionStorage. The key difference is that data stored in localStorage has no expiration time, while sessionStorage data is only available during the page session.

localStorage can only store strings, but you can store objects as JSON strings by using `JSON.stringify()` and retrieve them back using `JSON.parse()`.

Example

// Store data in localStorage localStorage.setItem('username', 'JohnDoe'); // Retrieve data from localStorage var user = localStorage.getItem('username'); // Remove data from localStorage localStorage.removeItem('username'); // Clear all localStorage localStorage.clear();

localStorage JavaScript Web Storage API persistent storage web development