Apa itu local storage di JavaScript?

Local storage allows developers to store and retrieve data in the browser. The data stored in local storage will not expire. This means the data will persist even if the tab or the browser window is closed.

Prerequisites

You must have a basic understanding of JavaScript. You also need a code editor and browser to test the project. In this tutorial, we will be using Visual Studio Code and Google Chrome.

What is local storage

Local storage is a form of web storage that stores data for a long time. This could be a day, a week, or even a year. This depends upon the developer’s preference. It is important to note that local storage only stores strings so, if you wish to store objects, lists, or arrays, you must convert them into a string using

window.localStorage.setItem("grade","One");
//in this case, the `grade` is the key while `One` is the value.
6

When to use local storage

You should only use local storage when storing insensitive information. This is because third-party individuals can easily access the information. Local storage can help in storing temporary data before it is pushed to the server. It is important to clear the local storage once this operation is completed.

Limitations

The major limitations of local storage are:

  • Insecure data.

  • Synchronous operations.

  • Limited storage capacity.

Main methods in local storage

The primary methods when using local storage are

window.localStorage.setItem("grade","One");
//in this case, the `grade` is the key while `One` is the value.
7,
window.localStorage.setItem("grade","One");
//in this case, the `grade` is the key while `One` is the value.
8,
window.localStorage.setItem("grade","One");
//in this case, the `grade` is the key while `One` is the value.
9,
const Car = {
  brand:"Suzuki",
  color:"white",
  price:10000
}

window.localStorage.setItem('car', JSON.stringify(Car));
0, and
const Car = {
  brand:"Suzuki",
  color:"white",
  price:10000
}

window.localStorage.setItem('car', JSON.stringify(Car));
1.

key()

This method is used to retrieve a value/string from a specific location. The index can be passed into the

window.localStorage.setItem("grade","One");
//in this case, the `grade` is the key while `One` is the value.
7 function as a parameter.

var answer = localStorage.key(1);
// this statement will retrieve the value of the second item in localStorage.

The

window.localStorage.setItem("grade","One");
//in this case, the `grade` is the key while `One` is the value.
7 can also be used in a loop statement to retrieve all the items in the local storage.

setItem()

This function is used to store items in local storage. An example of this function is shown below.

window.localStorage.setItem("grade","One");
//in this case, the `grade` is the key while `One` is the value.

As mentioned before, we must

const Car = {
  brand:"Suzuki",
  color:"white",
  price:10000
}

window.localStorage.setItem('car', JSON.stringify(Car));
4 objects before we store them in the local storage.

An example is outlined below:

const Car = {
  brand:"Suzuki",
  color:"white",
  price:10000
}

window.localStorage.setItem('car', JSON.stringify(Car));

Failure to stringify the object will result in an error.

getItem()

This function is used to access or retrieve the data in the local storage. The method takes in a

const Car = {
  brand:"Suzuki",
  color:"white",
  price:10000
}

window.localStorage.setItem('car', JSON.stringify(Car));
5 as a parameter. It then extracts the required value from the localSstorage.

For example, to retrieve the above

const Car = {
  brand:"Suzuki",
  color:"white",
  price:10000
}

window.localStorage.setItem('car', JSON.stringify(Car));
6 object, we will use the following statement:

window.localStorage.getItem('car');

The above statement will return something like this:

"{brand:"Suzuki",color:"white",price:"10000"}"

You should convert it to an object using

const Car = {
  brand:"Suzuki",
  color:"white",
  price:10000
}

window.localStorage.setItem('car', JSON.stringify(Car));
7 to use it in your code.

JSON.parse(window.localStorage.getItem('car'));

removeItem()

This method is used to delete an item from local storage. The

window.localStorage.setItem("grade","One");
//in this case, the `grade` is the key while `One` is the value.
9 method requires a key as a parameter.

window.localStorage.removeItem('brand');

clear()

This method is used to clear all values stored in local storage. It does not require any parameters.

window.localStorage.clear()

Project

Now that we have learned about the primary functions of local storage, let’s create a web application that stores, retrieves, deletes, and clears items from local storage.

Create a new folder and open it in your code editor. Create two files,

const Car = {
  brand:"Suzuki",
  color:"white",
  price:10000
}

window.localStorage.setItem('car', JSON.stringify(Car));
9 and
window.localStorage.getItem('car');
0. The
const Car = {
  brand:"Suzuki",
  color:"white",
  price:10000
}

window.localStorage.setItem('car', JSON.stringify(Car));
9 file will showcase the webpage to the user, while the
window.localStorage.getItem('car');
0 file will store our JavaScript functions. These functions will be used to access different functionalities of local storage.

Let’s Code

Our

const Car = {
  brand:"Suzuki",
  color:"white",
  price:10000
}

window.localStorage.setItem('car', JSON.stringify(Car));
9 will have a
window.localStorage.getItem('car');
4 and several
window.localStorage.getItem('car');
5, as shown below.

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Local Storage</title>
  <script type="text/javascript" src="main.js"></script>
</head>
<body>
  <div id="formDiv">
        <form id="carForm">
            <h1>Local Storage</h1>
            <label for="carBrand" >Car</label>
            <input type="text" id="carBrand" placeholder="Car brand" required autofocus><br>
            <label for="carPrice" >Price</label>
            <input type="text" id="carPrice" placeholder="Price" required><br>
            <label for="key" >Key</label>
            <input type="text" id="key" placeholder="Key" required><br>
            <button type="submit">Store Records</button>
        </form>
        <br>
        <label for="retrieveKey" >Enter Key to retrieve item</label>
        <input type="text" id="retrieveKey" placeholder="retrieveKey" required><br>
        <button id="retrieveButton">Retrieve records</button>
        <br>
        <div id="retrieve"></div>
        <br>
        <label for="removeKey" >Enter Key to delete item</label>
        <input type="text" id="removeKey" placeholder="removeKey" required><br>
        <button id="removeButton">Remove record</button>
        <br>
        <button id="clearButton">Clear all records</button>
  </div>
</body>
</html>

When the

window.localStorage.getItem('car');
6 button is clicked, it takes the user input and passes it to the
window.localStorage.getItem('car');
7 function in the
window.localStorage.getItem('car');
0 file. The
window.localStorage.getItem('car');
9 gets the user input. These values are then passed to the car object and stored in local storage using the
"{brand:"Suzuki",color:"white",price:"10000"}"
0 method.

function store(){ //stores items in the localStorage
    var brand = document.getElementById('carBrand').value;
    var price = document.getElementById('carPrice').value;
    var key = document.getElementById('key').value; //gets the key from the user

    const car = {
        brand: brand,
        price: price,
    }

    window.localStorage.setItem(key,JSON.stringify(car));  
    //converting object to string
}

Similarly, the

"{brand:"Suzuki",color:"white",price:"10000"}"
1 will invoke the
"{brand:"Suzuki",color:"white",price:"10000"}"
2 function when clicked. This method fetches items from the localStorage using the getItem function.

"{brand:"Suzuki",color:"white",price:"10000"}"
3 creates a new paragraph component in our web page.

"{brand:"Suzuki",color:"white",price:"10000"}"
4 helps create the text that will be displayed to the user.

The text node is then added to the paragraph tag by

"{brand:"Suzuki",color:"white",price:"10000"}"
5.

These components are then shown in a specific place on the web page by

"{brand:"Suzuki",color:"white",price:"10000"}"
6 and
"{brand:"Suzuki",color:"white",price:"10000"}"
7.

window.localStorage.setItem("grade","One");
//in this case, the `grade` is the key while `One` is the value.
0

"{brand:"Suzuki",color:"white",price:"10000"}"
8 invokes
window.localStorage.setItem("grade","One");
//in this case, the `grade` is the key while `One` is the value.
9. This
JSON.parse(window.localStorage.getItem('car'));
0 will delete a value from the local storage using the
JSON.parse(window.localStorage.getItem('car'));
1 function.

window.localStorage.setItem("grade","One");
//in this case, the `grade` is the key while `One` is the value.
1

JSON.parse(window.localStorage.getItem('car'));
2 calls the
JSON.parse(window.localStorage.getItem('car'));
3. The
const Car = {
  brand:"Suzuki",
  color:"white",
  price:10000
}

window.localStorage.setItem('car', JSON.stringify(Car));
1 method is used to remove all values in the local storage.

window.localStorage.setItem("grade","One");
//in this case, the `grade` is the key while `One` is the value.
2

Let’s set the

JSON.parse(window.localStorage.getItem('car'));
5 property of all the buttons when the webpage loads.

window.localStorage.setItem("grade","One");
//in this case, the `grade` is the key while `One` is the value.
3

Here is the

window.localStorage.getItem('car');
0 file with all the functions:

window.localStorage.setItem("grade","One");
//in this case, the `grade` is the key while `One` is the value.
4

As shown above, the functions will only be accessible after the page has finished loading. This is specified by the

JSON.parse(window.localStorage.getItem('car'));
7 method.

Ensure that the

window.localStorage.getItem('car');
0 file is referenced in the
const Car = {
  brand:"Suzuki",
  color:"white",
  price:10000
}

window.localStorage.setItem('car', JSON.stringify(Car));
9 file by pasting the statement below in the
window.localStorage.removeItem('brand');
0 section.

window.localStorage.setItem("grade","One");
//in this case, the `grade` is the key while `One` is the value.
5

Results

The following video shows how the site works:

Conclusion

You are now familiar with the different functionalities of local storage. The major methods in local storage are

"{brand:"Suzuki",color:"white",price:"10000"}"
0,
window.localStorage.removeItem('brand');
2,
JSON.parse(window.localStorage.getItem('car'));
1 and
window.localStorage.removeItem('brand');
4. A
const Car = {
  brand:"Suzuki",
  color:"white",
  price:10000
}

window.localStorage.setItem('car', JSON.stringify(Car));
5 is required when storing, retrieving, and removing items from the local storage. In case, you didn’t understand any concept, feel free to go through the local storage functions again.

Apa yang dimaksud dengan Web Storage?

Web storage adalah salah satu Web API yang dapat menyimpan data secara lokal pada sisi client. Berbeda dengan objek atau array, data yang disimpan pada objek atau array JavaScript bersifat sementara, dan akan hilang jika terjadi reload atau pergantian URL pada browser.

Apa perbedaan antara localStorage dan Sessionstorage?

Perbedaan antara local storage dan session storage yaitu, pada local storage data yang tersimpan tidak memiliki waktu expired (tidak ada batasan waktu penyimpanan), namun session storage data yang tersimpan akan hilang ketika kita menutup browser yang akan kita gunakan.

Apa kelebihan menyimpan data pada local storage dibandingkan dengan cookies?

Local storage dapat menyimpan data lebih aman dan lebih besar dibandingkan dengan cookie. Local storage juga dapat menyimpan data lebih dari 5 MB tanpa harus membebani performa browser.