Local Storage and Session Storage

Detailed view Local Storage and Session Storage

Local Storage and Session Storage

Local Storage

Local storage in JavaScript is a web storage feature that allows websites to store key-value pairs in a web browser, providing a way to persist data across sessions. It is part of the Web Storage API, which includes both localStorage and sessionStorage.

1. Overview of Local Storage

Local storage is a simple, synchronous, and client-side storage mechanism that allows you to store data (in the form of key-value pairs) in a user's browser. It provides a way to store small amounts of data (typically less than 5MB) that doesn't need to be sent to the server with each request.

  • Synchronous: Operations like setting, getting, and removing data in local storage are performed immediately.

  • Data is stored as strings: All data stored in local storage is converted to a string, so if you're working with non-string data types like arrays or objects, you need to serialize and deserialize them (typically using JSON.stringify and JSON.parse).

  • Scoped per domain: Local storage is accessible from any page on the same domain.

2. Basic API for Local Storage

The local storage object provides four key methods:

  • setItem(key, value): Stores the key-value pair in local storage.

  • getItem(key): Retrieves the value associated with the given key.

  • removeItem(key): Removes the key-value pair from local storage.

  • clear(): Clears all the data stored in local storage.

  • length: The number of stored items can be retrieved using localStorage.length.

Example of Basic Usage:

// Storing data in local storage
localStorage.setItem('username', 'JohnDoe');

// Retrieving data from local storage
let username = localStorage.getItem('username');
console.log(username);  // Output: 'JohnDoe'

// Removing a specific item
localStorage.removeItem('username');

// Clearing all local storage data
localStorage.clear();

3. Storing Non-String Data (Arrays, Objects, etc.)

As mentioned earlier, local storage only stores data as strings. To store other types of data (such as objects or arrays), you must convert them into a JSON string using JSON.stringify() and retrieve them back using JSON.parse().

Example of Storing Objects:

// Create an object
let user = {
  name: 'Vitthal Korvan',
  age: 24,
  profession: 'Developer'
};

// Convert object to JSON and store it in local storage
localStorage.setItem('user', JSON.stringify(user));

// Retrieve the object from local storage and parse it
let storedUser = JSON.parse(localStorage.getItem('user'));
console.log(storedUser.name);  // Output: 'Vitthal Korvan'

4. Checking for Local Storage Support

Before using local storage, it’s a good practice to check if the browser supports it, as older browsers may not support this feature.

if (typeof(Storage) !== 'undefined') {
  // Local storage is supported
  console.log('Local storage is supported.');
} else {
  // Local storage is not supported
  console.log('Local storage is not supported.');
}

5. Practical Use Cases of Local Storage

  • User Preferences: You can use local storage to save user settings, such as theme preferences (dark mode/light mode) or language selection.
// Store user theme preference
localStorage.setItem('theme', 'dark');

// Retrieve user theme preference
let theme = localStorage.getItem('theme');
document.body.classList.add(theme);

Session Storage

Session storage in JavaScript is a part of the Web Storage API that allows web applications to store data in a user’s browser for the duration of the page session. This means that data stored in session storage is specific to a particular tab or window and is cleared when the tab or window is closed.

Here’s a detailed overview of session storage:

1. Overview of Session Storage

Session storage is designed to store data that is relevant for the duration of a user's session on a web page. It is useful for temporary data that doesn’t need to persist after the user closes the browser tab or window.

  • Scope: Data stored in session storage is limited to the specific tab or window where it was created. If a user opens the same page in a new tab or window, a new session storage instance is created.

  • Data Lifetime: The data is available for the duration of the page session and is cleared when the tab or window is closed.

  • Synchronous: Operations are performed synchronously, which means they are executed immediately.

2. Basic API for Session Storage

The session storage object provides similar methods to local storage:

  • setItem(key, value): Stores the key-value pair in session storage.

  • getItem(key): Retrieves the value associated with the given key.

  • removeItem(key): Removes the key-value pair from session storage.

  • clear(): Clears all data stored in session storage.

  • length: The number of stored items can be accessed using sessionStorage.length.

Example of Basic Usage:

// Storing data in session storage
sessionStorage.setItem('username', 'Vitthal');

// Retrieving data from session storage
let username = sessionStorage.getItem('username');
console.log(username);  // Output: 'vitthal'

// Removing a specific item
sessionStorage.removeItem('username');

// Clearing all session storage data
sessionStorage.clear();

3. Storing Non-String Data (Arrays, Objects, etc.)

Like local storage, session storage only stores data as strings. To store non-string data types, you need to serialize them using JSON.stringify() and deserialize them using JSON.parse().

Example of Storing Objects:

// Create an object
let user = {
  name: 'Vitthal',
  age: 24,
  profession: 'Developer'
};

// Convert object to JSON and store it in session storage
sessionStorage.setItem('user', JSON.stringify(user));

// Retrieve the object from session storage and parse it
let storedUser = JSON.parse(sessionStorage.getItem('user'));
console.log(storedUser.name);  // Output: 'Vitthal'

4. Checking for Session Storage Support

Before using session storage, it’s good practice to check if the browser supports it.

if (typeof(Storage) !== 'undefined') {
  // Session storage is supported
  console.log('Session storage is supported.');
} else {
  // Session storage is not supported
  console.log('Session storage is not supported.');
}

5. Practical Use Cases of Session Storage

  • Form Data Preservation: Store user input temporarily while navigating between pages. If the user refreshes or accidentally navigates away, their data remains intact.
// Store form data temporarily
sessionStorage.setItem('formData', JSON.stringify({name: 'Vitthal', age: 24}));

// On page load, retrieve data
let formData = JSON.parse(sessionStorage.getItem('formData'));
console.log(formData.name);  // Output: 'Vitthal'

GitHub Link : GitHub - JavaScript Mastery