Storage
JavaScript provides two main types of client-side storage: localStorage and sessionStorage. Both of these storage options allow web developers to store data on the client’s machine, making it persistent across page reloads and even browser sessions.
1. localStorage:
localStorage is a type of web storage that allows you to store key/value pairs in a web browser with no expiration time. The data will persist even after the browser is closed and reopened.
Usage:
Setting a value:
localStorage.setItem(‘username’, ‘john_doe’);
Getting a value:
Removing a value:
localStorage.removeItem(‘username’);
Example:
// Store data
localStorage.setItem(‘username’, ‘john_doe’);
// Retrieve data
let storedUsername = localStorage.getItem(‘username’);
document.write (“Username:”, storedUsername);
// Remove data
localStorage.removeItem(‘username’);
2. SessionStorage:
sessionStorage is similar to localStorage, but the data stored in sessionStorage is only available for the duration of the page session. Once the browser tab or window is closed, the data is cleared.
Usage:
Setting a value:
sessionStorage.setItem(‘theme’, ‘dark’);
Getting a value:
let theme = sessionStorage.getItem(‘theme’);
document.write (“Theme:”, theme);
Removing a value:
sessionStorage.removeItem(‘theme’);
Example:
// Store data for the session
sessionStorage.setItem(‘theme’, ‘dark’);
// Retrieve data
let theme = sessionStorage.getItem(‘theme’);
document.write (“Theme:”, theme);
// Remove data
sessionStorage.removeItem(‘theme’);
3. Cookies (Document.cookie):
document.cookie provides a way to store small amounts of data that persist across requests. Unlike localStorage and sessionStorage, cookies have an expiration date.
Usage:
Setting a cookie:
document.cookie = ‘user=alice; expires=Thu, 31 Dec 2023 23:59:59 GMT; path=/’;
Getting a cookie:
let userCookie = document.cookie.split(‘; ‘).find(row => row.startsWith(‘user=’)).split(‘=’)[1];
document.write (“User Cookie:”, userCookie);
Removing a cookie (by setting expiration date to the past):
document.cookie = ‘user=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/’;
Example:
// Set a cookie
document.cookie = ‘user=alice; expires=Thu, 31 Dec 2023 23:59:59 GMT; path=/’;
// Retrieve cookie
let userCookie = document.cookie.split(‘; ‘).find(row => row.startsWith(‘user=’)).split(‘=’)[1];
document.write (“User Cookie:”, userCookie);
// Remove cookie (by setting expiration date to the past)
document.cookie = ‘user=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/’;
Note:
– Always be mindful of the data you store, especially in cookies, as it’s accessible on the client side.
– Cookies have a size limitation (usually around 4KB), while localStorage and sessionStorage can store more data.
– localStorage and sessionStorage store data as strings, so you may need to parse the data when retrieving it.
Here is the list of Storage
Method |
Description |
Example |
localStorage | Allows you to store key/value pairs in the browser’s local storage, persisting data even after the browser is closed | localStorage.setItem(‘username’, ‘JohnDoe’) stores the string ‘JohnDoe’ under the key ‘username’ in local storage |
sessionStorage | Allows you to store key/value pairs in the browser’s session storage, which is cleared when the browser is closed | sessionStorage.setItem(‘theme’, ‘dark’) stores the string ‘dark’ under the key ‘theme’ in session storage |
cookies | Allows you to store data in small text files on the user’s computer, often used for persisting user preferences or login information | document.cookie = ‘username=JohnDoe’ sets a cookie with the name ‘username’ and the value ‘JohnDoe’ |
setItem(key, value) | Stores a key/value pair in local or session storage | localStorage.setItem(‘username’, ‘JohnDoe’) stores the string ‘JohnDoe’ under the key ‘username’ in local storage |
getItem() | Retrieves the value associated with the given key from local or session storage | localStorage.getItem(‘username’) returns the string ‘JohnDoe’ (assuming it was previously stored under the key ‘username’ in local storage) |
removeItem() | Removes the key/value pair associated with the given key from local or session storage | localStorage.removeItem(‘username’) removes the key/value pair associated with the key ‘username’ from local storage |
clear() | Removes all key/value pairs from local or session storage | localStorage.clear() removes all key/value pairs from local storage |
JSON.parse(string) | Parses a JSON string and returns the corresponding JavaScript object | JSON.parse(‘{“name”:”John”, “age”:30}’) returns the JavaScript object {name: “John”, age: 30} |
JSON.stringify(object) | Converts a JavaScript object into a JSON string | JSON.stringify({name: “John”, age: 30}) returns the JSON string {“name”:”John”,”age”:30} |