Difference between Local Storage, Session Storage, and Cookies in JavaScript

JavaScript provides three mechanisms for storing data on the client ? cookies, session storage, and local storage. Each one has advantages and disadvantages.

Local storage is the most recent mechanism. It allows for larger amounts of data to be stored, but the data is not deleted when the browser is closed. Local storage is useful for storing data that the user will need to access later, such as offline data.

Session storage is similar to cookies, but the data is only stored for the current session. This means that the data will be deleted when the user closes the browser. Session storage is useful for storing data that is sensitive, such as login credentials.

Cookies are the oldest and most well-known mechanism. They are simple to use and well supported by browsers. However, they are limited to 4KB of data and are often used to store data that is not sensitive, such as user preferences.

In this tutorial, we are going to look at each of them in detail.

Local Storage

Local Storage is a type of web storage that allows JavaScript to store and access data right in the browser. This is especially useful for storing data that you want to persist even if the user closes the browser, such as preferences or settings.

The data in Local Storage is stored in key/value pairs. The key is like the name of the data, and the value is like the actual data itself.

Storing Data in Local Storage

To store data in Local Storage, you use the setItem() method. This method takes two arguments: the key and the value you want to store.

<script>
// Store data
localStorage.setItem('username', 'john_doe');
localStorage.setItem('theme', 'dark');

// Store an object (must be stringified)
let userSettings = { fontSize: 16, language: 'en' };
localStorage.setItem('settings', JSON.stringify(userSettings));

console.log('Data stored successfully');
</script>

Retrieving Data from Local Storage

To retrieve data from Local Storage, you use the getItem() method. This method takes the key as an argument and returns the data stored under that key.

<script>
// Store some data first
localStorage.setItem('username', 'john_doe');
localStorage.setItem('settings', JSON.stringify({ fontSize: 16, language: 'en' }));

// Retrieve data
let username = localStorage.getItem('username');
let settingsJson = localStorage.getItem('settings');
let settings = JSON.parse(settingsJson);

console.log('Username:', username);
console.log('Settings:', settings);
</script>
Username: john_doe
Settings: {fontSize: 16, language: 'en'}

Removing Data from Local Storage

To remove an item from Local Storage, use the removeItem() method. This method takes the key as an argument.

<script>
// Store and then remove data
localStorage.setItem('tempData', 'This will be removed');
console.log('Before removal:', localStorage.getItem('tempData'));

localStorage.removeItem('tempData');
console.log('After removal:', localStorage.getItem('tempData'));
</script>
Before removal: This will be removed
After removal: null

Session Storage

Session Storage is a type of web storage that allows web applications to store data locally within the user's browser. Unlike cookies, data stored in session storage is specific to the site and browser tab where it was created.

Session Storage is similar to local storage, but with key differences:

  • Session Storage data is only available for the duration of the browser tab session.

  • Session Storage data is not shared between browser tabs.

  • Session Storage data is automatically deleted when the tab is closed.

  • Session Storage data is specific to the browser tab in which it was created.

Using Session Storage

Session Storage uses the same methods as Local Storage but with the sessionStorage object.

<script>
// Store data in session storage
sessionStorage.setItem('currentUser', 'jane_smith');
sessionStorage.setItem('cartItems', JSON.stringify(['item1', 'item2']));

// Retrieve data
let currentUser = sessionStorage.getItem('currentUser');
let cartItems = JSON.parse(sessionStorage.getItem('cartItems'));

console.log('Current user:', currentUser);
console.log('Cart items:', cartItems);
console.log('Storage length:', sessionStorage.length);
</script>
Current user: jane_smith
Cart items: ['item1', 'item2']
Storage length: 2

Cookies

A cookie is a small piece of data that is stored on the user's computer. Cookies are used to store information about the user such as their name, preferences, and session data.

Cookies are created using the document.cookie property. Unlike localStorage and sessionStorage, cookies are automatically sent to the server with every HTTP request.

Setting a Cookie

A cookie is set by assigning a string to document.cookie. The string should be in the format "name=value".

<script>
// Set simple cookies
document.cookie = "username=john_doe";
document.cookie = "theme=dark";

// Set cookie with expiration date
let expiryDate = new Date();
expiryDate.setTime(expiryDate.getTime() + (7 * 24 * 60 * 60 * 1000)); // 7 days
document.cookie = "preference=newsletter; expires=" + expiryDate.toUTCString();

console.log('Cookies set successfully');
console.log('All cookies:', document.cookie);
</script>
Cookies set successfully
All cookies: username=john_doe; theme=dark; preference=newsletter

Reading Cookies

Reading cookies requires parsing the document.cookie string since it returns all cookies as a single string.

<script>
// Set a cookie first
document.cookie = "testCookie=testValue";

// Function to get cookie value
function getCookie(name) {
    let nameEQ = name + "=";
    let cookies = document.cookie.split(';');
    for(let i = 0; i < cookies.length; i++) {
        let cookie = cookies[i].trim();
        if (cookie.indexOf(nameEQ) === 0) {
            return cookie.substring(nameEQ.length);
        }
    }
    return null;
}

let cookieValue = getCookie('testCookie');
console.log('Cookie value:', cookieValue);
</script>
Cookie value: testValue

Comparison of Storage Methods

The following table highlights the major differences between Local Storage, Session Storage, and Cookies:

Feature Local Storage Session Storage Cookies
Storage Capacity ~10MB ~5MB 4KB
Persistence Until manually cleared Until tab is closed Until expiration date
Sent to Server No No Yes (with every request)
Browser Support HTML5 (IE8+) HTML5 (IE8+) All browsers (HTML4)
Scope Origin-wide Tab-specific Domain-wide
Best Use Cases User preferences, offline data Form data, temporary state Authentication, tracking

Conclusion

Local Storage is ideal for data that needs to persist across browser sessions, Session Storage works best for temporary data within a single tab session, and Cookies are essential when you need to send data to the server automatically. Choose the storage method based on your specific requirements for data persistence, capacity, and server communication.

Updated on: 2026-03-15T23:19:00+05:30

44K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements