What is Local Storage in JavaScript - onlyxcodes

Monday 26 June 2023

What is Local Storage in JavaScript

Local storage in JavaScript refers to a feature of web browsers that enables web applications to store data locally on a user's system. It offers an easy key-value storage system that endures even after the user closes the browser or restarts the computer.


This information is particular to a given domain and is accessible until specifically cleared by the user or by programmed means.


The Web Storage API, which also covers session storage, provides local storage. Local storage, as opposed to session storage, has no time limit and is kept on the device until it is erased.


local storage in javascript

Table Content

1. What is localStorage in JavaScript?

2. What is Window.localStorage?

3. How to Work with localStorage?

4. How to Store Data in localstorage in Javascript

5. How to store a JavaScript Array in localStorage

6. How to Display Data from localstorage in JavaScript

7. How to Display Array Item from localstorage in JavaScript

8. How to get all Data from LocalStorage using For Loop

9. How to Update LocalStorage value in JavaScript

10. How to Remove Data from LocalStorage in JavaScript

11. How to Clear Data from localstorage in JavaScript

12. FAQs


What is localStorage in JavaScript?

JavaScript websites and applications can store key-value pairs in a web browser without a time limit by using the localStorage attribute. This indicates that the data is persistent even if the user closes the browser or restarts the computer.


Since localStorage is a window object property, it can interact with and influence the browser window as a global object. Additionally, it can be used in association with other window methods and attributes.


What is Window.localStorage?

The window.localStorage attribute provides access to the localStorage mechanism. 


The Window interface in JavaScript represents a window containing a DOM document and includes a local storage component called Window.localStorage. 


There are many different functions, constructors, objects, and namespaces available in the Window interface. 


A reference to the local storage object used to store data that is only available to the origin that created it is returned by the read-only attribute window.localStorage.


How to Work with localStorage?

JavaScript users can access the window.localStorage property, which offers numerous methods like setItem(), getItem(), and removeItem(), to use local storage. These enable the storing, reading, and deletion of key-value pairs.


How to Store Data in localstorage in Javascript

The setItem() function of the localStorage object can be used to store data in local storage. A key and a value are the two arguments needed for this method. 


The value can be any data type that JavaScript supports, such as text, number, or boolean. The key is a string that uniquely identifies the data you want to save. A string can be stored in LocalStorage using the following example:


window.localStorage.setItem('myKey', 'myValue');

Example:


"Australia" is the key and "New South Wales" is the value in this situation.


window.localStorage.setItem('Australia', 'New South Wales');

How to store a JavaScript Array in localStorage?

An array or object must be converted to a string before being stored. JSON.stringify() allows you to turn an object or array into a string.


Example:


const country = {
	name: "Australia",
	state: "New South Wales",
	capital: "Sydney"
}
	
const price = [1500, 1000, 8000, 2000];
 
window.localStorage.setItem('world',  JSON.stringify(country));
window.localStorage.setItem('iphone', JSON.stringify(price));

How to Display Data from localstorage in JavaScript

Use the getItem() function to display data from LocalStorage. The key to the data you want to obtain is the only argument required by this method. 


If the key doesn't exist in LocalStorage, the method returns null, else it returns the value related to the key.


Here is an illustration of how to get a key's value out of LocalStorage:


window.localStorage.getItem('myKey');

Example:


window.localStorage.setItem('Australia', 'New South Wales');

let data = window.localStorage.getItem('Australia');
	
console.log(data);

Output:


New South Wales

How to Display Array Item from localstorage in JavaScript

const country = {
	name: "Australia",
	state: "New South Wales",
	capital: "Sydney"
}
	
const price = [1500, 1000, 8000, 2000];
 
window.localStorage.setItem('world',  JSON.stringify(country));
window.localStorage.setItem('iphone', JSON.stringify(price));

let data1 = window.localStorage.getItem('world');
let data2 = window.localStorage.getItem('iphone');
	
console.log(data1);
console.log(data2);

It will shows the below output:


{"name":"Australia","state":"New South Wales","capital":"Sydney"}
[1500,1000,8000,2000]

Use the JSON.parse() method if you wish to transform the output from a string to an object.


const country = {
	name: "Australia",
	state: "New South Wales",
	capital: "Sydney"
}
	 
window.localStorage.setItem('world',  JSON.stringify(country));

let data = JSON.parse(window.localStorage.getItem('world'));
	
console.log(data);

It will displa following output:


{name: 'Australia', state: 'New South Wales', capital: 'Sydney'}

How to get all Data from LocalStorage using For Loop

Using a for loop, you can traverse through each object in localStorage.


The index is a valid input for the key() method, which returns the key that corresponds to it. 


The key is a parameter to the getItem() method, which returns the value associated with it. Finally, the key-value pair is printed via the console.log() method.


const country = {
    name: "Australia",
    state: "New South Wales",
    capital: "Sydney"
}

window.localStorage.setItem('world',  JSON.stringify(country));

for (let i = 0; i < localStorage.length; i++)
{
    let key = localStorage.key(i);
    let value = localStorage.getItem(key);
    console.log(key, value);
}

How to Update LocalStorage value in JavaScript

You can use the setItem() method once again with the same key if you want to update the value of a stored item. It will replace the current value.


Here's an illustration:


window.localStorage.setItem('Australia', 'New South Wales');

//update
window.localStorage.setItem('Australia', 'Western Australia');

let data = window.localStorage.getItem('Australia');
console.log(data);

Output:


Here, we first obtain the key of 'Australia' using the getItem() method, after which the updated value of 'Western Australia' rather than 'New South Wales' is displayed.


Western Australia

How to Remove Data from LocalStorage in JavaScript

The removeItem() method can be used to remove data from LocalStorage. The key to the data you want to remove is the only argument required for this method. 


The key-value pair connected to the key is deleted from LocalStorage by the method.


An illustration of how to delete a key-value pair from LocalStorage is shown below:


window. localStorage.removeItem('myKey');

Example:


window.localStorage.removeItem('Australia');

How to Clear Data from localstorage in JavaScript

Use the clear() function to clear every item from localStorage if you want to. The entire localStorage object is cleared. 


Here's an illustration:


window.localStorage.clear();

Note: If the data is not explicitly cleared or destroyed, it continues to exist even after quitting and reopening the browser.


When using localStorage, make sure to take care of any potential mistakes. Be aware of the size of the data you save because, depending on the browser, the data stored in localStorage is restricted to a few megabytes.


Frequently Asked Questions

What is the difference between localstorage and sessionstorage?


Although web browsers offer both LocalStorage and SessionStorage as web storage options, their scope and persistence are different.


LocalStorage:


Scope: Web applications can store data locally and indefinitely using LocalStorage in the user's web browser.


Persistence: Even if the browser window is closed, the information stored in LocalStorage is still accessible during the next session.


Shared across tabs: All tabs and windows with the same origin (same domain, protocol, and port) share LocalStorage. In other words, information kept in LocalStorage in one tab is available in another tab or window of the same website.


Size limit: LocalStorage typically has a size limit of 5MB, though this can vary significantly between browsers.


SessionStorage:


Scope: As the name implies, SessionStorage holds information for a single session. An individual surfing session in a certain tab or window is referred to as a session.


Persistence: SessionStorage data is erased when the browser window or tab is closed, unlike LocalStorage. It is designed to be used for transient information that is only required during the session.


Isolated per tab: SessionStorage is available in different instances for each tab or window. In another tab or window of the same website, the data stored in SessionStorage in one tab is not available.


Size limit: Similar to LocalStorage, SessionStorage has a common size limit of about 5MB, though this can vary significantly depending on the browser.


In conclusion, while SessionStorage offers temporary storage isolated for each tab and limited to a single session, LocalStorage offers persistent storage over several sessions and tabs. Depending on the particular needs and expected lifetime of the data, both storage techniques are appropriate for storing data in web applications.


What is the difference between cookies and local storage?


Web browsers employ both cookies and local storage as methods to store data on a user's device. However, there are a number of significant variations between the two:


Data storage: 


Cookies are tiny text files with a maximum data storage capacity of 4 KB. Every request and answer involves sending them back and forth between the web server and the browser. 


Local storage, on the other hand, has a bigger storage capacity within the browser (usually 5MB) and is not transferred immediately with every server request.


Data retention: 


Cookies have a validity period and can be configured to persist for a predetermined amount of time or until the user closes their browser. 


On the other hand, unless manually deleted or deleted by the web application, local storage stays stored on the user's device eternally.


Data accessibility: 


Cookies are usable for server-side and client-side operations since they may be accessed from both the client-side (JavaScript) and the server-side (HTTP headers). 


Local storage can only be accessed from the client-side, hence JavaScript is the only language that can be used to change it.


Network traffic: 


Every HTTP request that is delivered to the server contains cookies, which increases the amount of network traffic. 


Local storage does not affect network traffic because it is contained within the browser.


Purpose: 


Cookies were initially created to make state management easier and to support features like persistent sessions and user monitoring. They can also be used for personalisation and authentication. 


On the other hand, local storage is mostly designed for client-side data storage of greater amounts, including user preferences or application-specific data.


It's important to note that both cookies and local storage have their own specific use cases and limitations, and the choice between them depends on the requirements of the web application or website.


It's crucial to note that the decision between cookies and local storage relies on the needs of the online application or website. Each has unique use cases and rules.

No comments:

Post a Comment

Post Bottom Ad