Storages In Javascript

March 14, 2023, 10:03 p.m.

web development javascript

In JavaScript, there are several options for storing data locally within a web browser, including cookies, local storage, and session storage. These storage options can be used to save user preferences, login information, and other data that needs to persist between sessions or page refreshes.

Cookies:

Cookies are small pieces of data that are stored on the user's computer by the web server. They are commonly used to store user preferences or login information, so that the user does not need to enter this information every time they visit the website. Cookies are limited in size and can only store a few kilobytes of data. They are also subject to security risks, as they can be accessed by third-party websites and can potentially be used to track user activity.

Local Storage:

Local storage is a newer feature of web browsers that allows developers to store larger amounts of data locally within the browser. Local storage is accessed through the localStorage object in JavaScript, and can be used to store data as key-value pairs. The data stored in local storage persists even after the browser is closed, and can be accessed by any page within the same domain. However, local storage is limited in size, typically to 5-10 megabytes depending on the browser.

Session Storage:

Session storage is similar to local storage, but is scoped to the current browser session. Data stored in session storage is only available to the current tab or window, and is deleted when the browser is closed. Session storage is accessed through the sessionStorage object in JavaScript, and can also be used to store data as key-value pairs.

Example

Here is an example of how to use local storage in JavaScript:

// Store data in local storage
localStorage.setItem('username', 'John');
localStorage.setItem('color', 'blue');

// Retrieve data from local storage
const username = localStorage.getItem('username');
const color = localStorage.getItem('color');
console.log(`Welcome back, ${username}! Your favorite color is ${color}.`);

In this example, the setItem() method is used to store the user's username and favorite color in local storage. The getItem() method is then used to retrieve the data from local storage and display a welcome message to the user.

It is important to note that local storage and session storage are not secure, and should not be used to store sensitive information such as passwords or credit card numbers. For secure storage of sensitive data, server-side storage options such as databases should be used instead.

author image

bracketcoders

A learing portal for your coding interest.

View Profile