Storage API Methods

The Web Storage API provides methods for reading, writing, removing, and clearing string key-value data in browser storage. The main methods are `getItem()`, `setItem()`, `removeItem()`, and `clear()`.

Web Storage exposes a `Storage` interface through objects such as `localStorage` and `sessionStorage`. Data is stored as key-value pairs, and both keys and values are represented as strings.

Use `setItem(key, value)` to create or replace an entry. Use `getItem(key)` to retrieve a value; if the key does not exist, it returns `null`.

Use `removeItem(key)` to delete one entry. Use `clear()` to remove all entries from that particular `Storage` object.

`localStorage` persists across browser sessions, while `sessionStorage` is associated with the current page session. Web Storage is synchronous, so it is best suited to relatively small amounts of client-side data rather than large or performance-sensitive datasets.

Key points

Interview questions

What is the difference between `removeItem()` and `clear()`?

`removeItem()` takes a key and deletes only that entry. `clear()` takes no key and removes every entry belonging to that `Storage` object. Therefore, `clear()` is much broader and should be used carefully when other stored application data may exist.

What are the main methods on the Web Storage API?

The core methods are `getItem()`, `setItem()`, `removeItem()`, and `clear()`. `setItem()` writes a value, while `getItem()` reads it. `removeItem()` deletes one key, and `clear()` removes all keys from that storage object. These methods are available on both `localStorage` and `sessionStorage`.

What happens when you call `setItem()` with a key that already exists?

The existing value for that key is replaced with the new value. Web Storage uses the key to identify an entry, so a second `setItem()` with the same key updates that entry rather than creating a duplicate key. The stored value is represented as a string.

What does `getItem()` return when the key does not exist?

It returns `null` when there is no entry for the requested key. This is different from `undefined`, so code should test for `null` when distinguishing a missing entry. If the stored value itself can have application-specific meanings, the application should define how those cases are handled.

What are important limitations of Web Storage?

Web Storage stores string key-value data and exposes a synchronous API. That simplicity makes it convenient for small client-side state, but it is not a general-purpose database. Developers also need to consider storage limits, browser behavior, and the fact that client-side storage should not be treated as a secure place for sensitive secrets.