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.

var x = 5;
localStorage.setItem("id", x);

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

var x = 5;
localStorage.setItem("id", x);
localStorage.getItem("id"); //Will display x.

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!

<!--HTML-->
<button onclick="add_point()">Click me!</button>

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!

var x; //Is not defined yet.
function add_point() {
    //If the variable localStorage.clickcount DOES exist
    if (Number(localStorage.clickcount)) {
      localStorage.clickcount = Number(localStorage.clickcount)+1; //Add point
      x = localStorage.clickcount;  //x is now defined!
      x = Number(x) //Since localStorage only accepts strings, we will turn this into a numbed using Number(x)
    } 
    //If the variable localStorage.clickcount does NOT exist, it creates the variable, and its value will be 1
    else {
      localStorage.clickcount = 1;
    }
  document.getElementById("points").innerHTML = "Points: " + x;
}

Now lets update the HTML code:

<!--HTML-->
<button onclick="add_point()">Click me!</button>
<div id="points"></div>

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.