Saturday, April 1, 2023
Learning Code
  • Home
  • JavaScript
  • Java
  • Python
  • Swift
  • C++
  • C#
No Result
View All Result
  • Home
  • JavaScript
  • Java
  • Python
  • Swift
  • C++
  • C#
No Result
View All Result
Learning Code
No Result
View All Result
Home JavaScript

How to Use localStorage in JavaScript

learningcode_x1mckf by learningcode_x1mckf
September 18, 2022
in JavaScript
0
How to Use localStorage in JavaScript
74
SHARES
1.2k
VIEWS
Share on FacebookShare on Twitter


The localStorage mechanism offers a kind of internet storage object that permits you to retailer and retrieve information within the browser. You possibly can retailer and entry information with out expiration; the information might be out there even after a customer closes your web site.

You’ll usually entry localStorage utilizing JavaScript. With a small quantity of code, you may construct a pattern challenge, like a rating counter. It will present how one can retailer and entry persistent information utilizing solely client-side code.


What Is localStorage in JavaScript?

The localStorage object is a part of the net storage API that almost all internet browsers help. You possibly can retailer information as key-value pairs utilizing localStorage. The distinctive keys and values needs to be within the UTF-16 DOM String format.

If you wish to retailer objects or arrays, you will should convert them to strings utilizing the JSON.stringify() methodology. You possibly can retailer as much as 5MB of information in localStorage. Additionally, all home windows with the identical origin can share that web site’s localStorage information.

A browser won’t delete this information even when a person closes it. It will likely be out there to the web site that created it throughout any future session. Nonetheless, you should not use localStorage for delicate information since different scripts working on the identical web page can entry it.

localStorage vs. sessionStorage

The localStorage and sessionStorage objects are a part of the Net Storage API that shops key-value pairs regionally. All fashionable browsers help them each. With localStorage, the information doesn’t expire even after a person closes their browser. This differs from sessionStorage which clears information when the web page session ends. A web page session ends if you shut a tab or window.

The code used on this challenge is offered in a GitHub repository and is free so that you can use below the MIT license. If you wish to take a look at a reside model of the rating counter challenge, you may try the reside demo.

How Does localStorage Work?

You possibly can entry the localStorage performance by means of the Window.localStorage property. This property offers a number of strategies like setItem(), getItem(), and removeItem(). You should utilize these to retailer, learn, and delete key/worth pairs.

Methods to Retailer Information in localStorage

You possibly can retailer information in localStorage utilizing the setItem() methodology. This methodology accepts two arguments, the important thing, and the corresponding worth.

window.localStorage.setItem('Python', 'Guido van Rossum');

Right here, Python is the important thing and Guido van Rossum is the worth. If you wish to retailer an array or an object, you’ll have to convert it to a string. You possibly can convert an array or an object right into a string utilizing the JSON.stringify() methodology.

window.localStorage.setItem('Python', 'Guido van Rossum');

const pupil =
identify: "Yuvraj",
marks: 85,
topic: "Machine Studying"

const scores = [76, 77, 34, 67, 88];
window.localStorage.setItem('end result', JSON.stringify(pupil));
window.localStorage.setItem('marks', JSON.stringify(scores));

Methods to Learn Information From localStorage

You possibly can learn information from localStorage utilizing the getItem() methodology. This methodology accepts the important thing as a parameter and returns the worth as a string.

let data1 = window.localStorage.getItem('Python');
let data2 = window.localStorage.getItem('end result');

console.log(data1);
console.log(data2);

This produces the next output:

Guido van Rossum
"identify":"Yuvraj","marks":85,"topic":"Machine Studying"

If you wish to convert the end result from a string to an object, you must use the JSON.parse() methodology.

let data2 = JSON.parse(window.localStorage.getItem('end result'));
console.log(data2);

Methods to Delete localStorage Classes

You possibly can delete localStorage periods utilizing the removeItem() methodology. You’ll want to move the important thing as a parameter to this methodology to delete the key-value pair. If the important thing exists, the tactic will delete the key-value pair and if the important thing doesn’t exist, the tactic will do nothing.

window.localStorage.removeItem('Python');
window.localStorage.removeItem('C++');

Methods to Clear All Objects in localStorage

You possibly can clear all gadgets in native storage utilizing the clear() methodology. You needn’t move any parameter to this methodology.

window.localStorage.clear();

Methods to Discover the Size of localStorage

Yow will discover the size of localStorage utilizing the localStorage.size property.

let len = localStorage.size;
console.log(len);

Methods to Get the Key at a Given Place

You will get the important thing on a given place utilizing the key() methodology. This methodology accepts the index as a parameter.

let d = localStorage.key(1);
console.log(d);

The important thing() methodology is primarily used to loop by means of all of the gadgets in localStorage.

Methods to Loop Via All of the Objects in localStorage

You possibly can iterate over all of the gadgets in localStorage utilizing a for loop.

for (let i = 0; i < localStorage.size; i++)
let key = localStorage.key(i);
let worth = localStorage.getItem(key);
console.log(key, worth);

The important thing() methodology accepts the index as an argument and returns the corresponding key. The getItem() methodology accepts the important thing as an argument and returns the corresponding worth. Lastly, the console.log() methodology prints the key-value pair.

Easy JavaScript Undertaking Based mostly on localStorage

With an understanding of its fundamental strategies, you may develop a simple JavaScript project based mostly on localStorage. On this challenge, you will create a rating counter app that can enhance and reduce the rating rely in keeping with a button click on. Additionally, you will implement performance to clear all gadgets in localStorage.

Create an index.html and script.js file in a brand new folder and open the information in your favourite code editor. Use the next HTML code to create an interface for the rating counter app:

<!DOCTYPE html>
<html>
<physique>
<h1>localStorage in JavaScript</h1>
<button onclick="increaseCounter()" sort="button">Enhance Rating</button>
<button onclick="decreaseCounter()" sort="button">Lower Rating</button>
<button onclick="clearCounter()" sort="button">Clear localStorage</button>
<p>Rating:</p>
<p id="rating"></p>
<p>Click on on the "Enhance Rating" button to extend the rating rely</p>
<p>Click on on the "Lower Rating" button to lower the rating rely</p>
<p>Click on on the "Clear localStorage" button to clear the localStorage</p>
<p>
You possibly can shut the browser tab (or window), and attempt once more.
You may see that the information nonetheless persists and is not misplaced even after closing
the browser.
</p>
<script src="script.js"> </script>
</physique>
</html>

This web page incorporates three buttons: Enhance Rating, Lower Rating, and Clear localStorage. These buttons name the increaseCounter(), decreaseCounter(), and clearCounter() features respectively. Use the next code so as to add performance to the rating counter app utilizing JavaScript.

operate increaseCounter() 
var rely = Quantity(window.localStorage.getItem("rely"));
rely += 1;
window.localStorage.setItem("rely", rely);
doc.getElementById("rating").innerHTML = rely;

The increaseCounter() operate retrieves the rely utilizing the getItem() methodology. It converts the end result right into a Quantity, since getItem() returns a string, and shops it within the rely variable.

The primary time you click on on the Enhance Rating button might be earlier than any name to setItem(). Your browser won’t discover the rely key in localStorage, so it should return a null worth. Because the Quantity() operate returns 0 for a null enter, it does not want any particular case dealing with. The code can safely enhance the rely worth earlier than storing it and updating the doc to show the brand new worth.

operate decreaseCounter() 
var rely = Quantity(window.localStorage.getItem("rely"));
rely -= 1;
window.localStorage.setItem("rely", rely);
doc.getElementById("rating").innerHTML = rely;

The decreaseCounter() operate retrieves and checks the information similar to increaseCounter() does. It decrements the rely variable by 1, which defaults to 0.

operate clearCounter() 
window.localStorage.clear();
doc.getElementById("rating").innerHTML = "";

Final, the clearCounter() operate deletes all the information from localStorage utilizing the clear() methodology.

Do Extra With localStorage

The localStorage object has a number of strategies together with setItem(), getItem(), removeItem(), and clear(). Whereas localStorage is simple to make use of, it’s not protected to retailer delicate info. But it surely’s a good selection to develop initiatives that do not require a lot storage and do not contain any delicate info.

Need to construct one other localStorage based mostly JavaScript challenge? Here is a fundamental to-do record app which you can develop utilizing HTML, CSS, and JavaScript.



Source link

You might also like

4 Packages for Working With Date and Time in JavaScript – MUO – MakeUseOf

Understanding the Power of Proxy in JavaScript – hackernoon.com

JavaScript vs. TypeScript: What's the difference? – TheServerSide.com

Share30Tweet19
learningcode_x1mckf

learningcode_x1mckf

Recommended For You

4 Packages for Working With Date and Time in JavaScript – MUO – MakeUseOf

by learningcode_x1mckf
April 1, 2023
0
Google expands open source bounties, will soon support Javascript fuzzing too – ZDNet

4 Packages for Working With Date and Time in JavaScript  MUO - MakeUseOf Source link

Read more

Understanding the Power of Proxy in JavaScript – hackernoon.com

by learningcode_x1mckf
April 1, 2023
0
Google expands open source bounties, will soon support Javascript fuzzing too – ZDNet

Understanding the Power of Proxy in JavaScript  hackernoon.com Source link

Read more

JavaScript vs. TypeScript: What's the difference? – TheServerSide.com

by learningcode_x1mckf
April 1, 2023
0
Google expands open source bounties, will soon support Javascript fuzzing too – ZDNet

JavaScript vs. TypeScript: What's the difference?  TheServerSide.com Source link

Read more

JetBrains updates IDEs for Java, JavaScript, Ruby – InfoWorld

by learningcode_x1mckf
March 31, 2023
0
Google expands open source bounties, will soon support Javascript fuzzing too – ZDNet

JetBrains updates IDEs for Java, JavaScript, Ruby  InfoWorld Source link

Read more

Virtru Announces First Ever FIPS 140-2 Validated JavaScript … – GlobeNewswire

by learningcode_x1mckf
March 30, 2023
0
Google expands open source bounties, will soon support Javascript fuzzing too – ZDNet

Virtru Announces First Ever FIPS 140-2 Validated JavaScript ...  GlobeNewswire Source link

Read more
Next Post
So why did they decide to call it Java?

So why did they decide to call it Java?

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Related News

Google expands open source bounties, will soon support Javascript fuzzing too – ZDNet

Oracle's new Java 20 programming language & development … – Daijiworld.com

March 24, 2023
Google expands open source bounties, will soon support Javascript fuzzing too – ZDNet

Conan C/C++ Package Manager 2.0 Now In Beta – iProgrammer

February 11, 2023
Time limit for notify – JavaScript – SitePoint Forums

Jquery Failing In Electron – JavaScript – SitePoint Forums

December 22, 2022

Browse by Category

  • C#
  • C++
  • Java
  • JavaScript
  • Python
  • Swift

RECENT POSTS

  • So why did they decide to call it Java? – InfoWorld
  • Senior Java Developer – IT-Online
  • 4 Packages for Working With Date and Time in JavaScript – MUO – MakeUseOf

CATEGORIES

  • C#
  • C++
  • Java
  • JavaScript
  • Python
  • Swift

© 2022 Copyright Learning Code

No Result
View All Result
  • Home
  • JavaScript
  • Java
  • Python
  • Swift
  • C++
  • C#

© 2022 Copyright Learning Code

Are you sure want to unlock this post?
Unlock left : 0
Are you sure want to cancel subscription?