Learn to Code via Tutorials on Repl.it!

← Back to all posts
How to save data in JavaScript using LocalStorage!
[deleted]

How to save data in JavaScript with localStorage!

Today you will learn how to save data in JavaScript with localStorage! We will be learning 2 methods. So lets get started! But first, an explanation:

What is localStorage?

localStorage is a method of web storage. It saves data for website. Other examples of web storage are cookies or databases. localStorage is not widely used but who cares! Now, lets get started!

Method 1

The first method is using the setItem method.

All it does is save the variable x to the localStorage. And to display x, we will use getItem:

And that's it for method 1! If you have any questions, just ask me and I will (try) to answer them! Now to method 2, which I like to use, but its a bit more complicated.

Method 2

Lets say we want to make a clicker game and you want to save the users progress, well no problem! Lets get started! Lets make a button in HTML that will do a function when clicked!

And nows the tricky part, which I will explain! We will create a variable called localStorage.clickCount. This variable represents the amount of times the button is clicked!

Now lets update the HTML code:

Conclusion

Its all in the comments in the code. So if you click the button, the points will be added! The difference between method 1 and 2 is because method 1 will always be the same, whereas method 2 is always updated and the data is saved! I hope you learned something new today and that concludes this tutorial, bye! And feel free to use the code as a template! And if you have any questions, just ask me! And thers just a random repl attached.

Voters
LSchiavone
CalSch
DynamicSquid