JavaScript LocalStorage – Tuts Make


In this tutorial, you will learn everything about javascript localStorage & as well as types of methods in localStorage. Also how to create a todo app using javascript localStorage.

Ezoic

If you are creating sites and apps in JavaScript. And If you do not want to store,read, and delete data into the database. So in that case, you can store, fetch, and remove the data locally in the user’s browser by using localStorage of JavaScript.

Table of Contents

  • What is LocalStorage in JavaScript?Ezoic
  • JavaScript localStorage methods
  • localStorage with condition statement Loop
  • JavaScript CRUD Operations with Local Storage
  • Advantage and Disadvantage of localStorage

What is LocalStorage in JavaScript?

In JavaScript, localStorage is a type of web storage that allows storing data locally within the user’s browser with no expiration date for javascript sites and apps. This data will not be deleted when the browser is closed and will be available when the browser is opened again.

JavaScript localStorage methods

There are six basic JavaScript localStorage methods to use localStorage in your web applications for access and work with localStorage:

  1. setItem(): Add key and value to localStorage
  2. getItem(): Retrieve a value by the key from localStorage
  3. removeItem(): Remove an item by key from localStorage
  4. clear(): Clear all localStorage
  5. key(): Passed a number to retrieve nth key of a localStorage
  6. length – the number of stored items.

localStorage setItem

localStorage setItem() method allows us to store data locally in key-value pairs within the user’s browser.

Ezoic

The following syntax represents the setItem() method:

localStorage.setItem(key, 'Value');

Here,

  • The key means by which name the data will be stored locally.
  • Value means what value you will store in the associate key.

Note that localStorage can only store strings.

localStorage getItem

localStorage getItem() method allows to fetch data using a particular key within the user’s browser

The following syntax represents the getItem() method:

Ezoic

 localStorage.getItem('key') 

Here,

Ezoic

  • The name of the key you want to retrieve the value of.

localStorage removeItem

localStorage removeItem() method allows to remove data using a particular key within the user’s browser

The following syntax represents the removeItem() method:

 localStorage.removeItem('key') 

Here,

  • The name of the key you want to delete the value of.

localStorage clear

localStorage clear() method allows to clear or delete all local storage data within the user’s browser

Ezoic

The following syntax represents the clear() method:

 localStorage.clear() 

localStorage key

localStorage key() method allows to passing a number or index to localStorage to retrieve the name of the key.

The following syntax represents the key() method:

localStorage.key(index);

localStorage length

localStorage length method allows to get the presence of items stored locally in the within the user’s browser:

The following syntax represents the length method:

localStorage.length

localStorage with Condition statement and Loop

If you want to check some items in localStorage, you can use javascript if else statement. The following example represents how to use localStorage data with if-else statement:

if (localStorage.length > 0) {
  // We have items
} else {
  // No items
}

Next, if you want to iterate localStorage data, you can use javascript for loop. The following example represents how to iterate localStorage items with for loop:

Ezoic

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

JavaScript CRUD Operations with Local Storage

Here’s a some steps on performing CRUD (Create, Read, Update, Delete) operations with Local Storage in JavaScript. Local Storage provides a simple way to store key-value pairs locally in a user’s browser.

First, we’ll create a simple HTML front end with index.html. And loading in the bootstrap library and style.css for styling to-do app.

Index.html

<!DOCTYPE html>
<html>
  <head>
    <link
      rel="stylesheet"
      href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/css/bootstrap.min.css"
      integrity="sha384-Zug+QiDoJOrZ5t4lssLdxGhVrurbmBWopoEl+M6BdEfwnCJZtKxi1KgxUyJq13dy"
      crossorigin="anonymous"
    />
    <link rel="stylesheet" type="text/css" href="src/styles.css" />
  </head>
  <body>
    <div
      class="body-overlay opacity-80"
      style="background-color: #151c54"
    ></div>
    <div class="container">
      <div class="header">
        <h1>TO DO LIST</h1>
      </div>
      <div class="input-group mb-3">
        <input
          type="text"
          class="form-control taskname"
          placeholder="Enter Your Task"
          aria-label="Recipient's username"
          aria-describedby="basic-addon2"
        />
        <div class="input-group-append">
          <button type="button" class="btn btn-primary btnTask">
            Add Task
          </button>
        </div>
      </div>
      <ul class="tasklist"></ul>
      <button type="button" class="btn btn-link btnClear">Clear All</button>
    </div>
    <script src="src/index.js"></script>
  </body>
</html>

Remember that, create one folder name src and as well as create two files first one is style.css and second one is scritp.js inside src folder.

Update the following CSS into your src/style.css file:

h1,
p {
  text-align: center;
}
body {
  color: #435757;
  background-image: url(https://learnwith.hasinhayder.com/wp/wp-content/uploads/2018/07/emile-perron-190221-unsplash-banner.jpg);
  background-color: linear-gradient(-20deg, #d0b782 20%, #a0cecf 80%);
  font-family: Roboto, sans-serif;
  height: 100vh;
  background-size: cover;
  background-repeat: no-repeat;
  background-position: center center;
}
.container {
  max-width: 570px;
  top: 125px;
  margin: 0 auto;
  padding: 12px 25px 50px;
  border-top: 5px solid rgba(255, 255, 255, 0.16);
  background: linear-gradient(
    to right,
    #0dabf31c 0,
    #2b2f5c00 51%,
    #2a2e5b00 100%
  );
  background-color: rgba(22, 27, 72, 0.83);
  user-select: none;
  z-index: 100;
  position: relative;
  box-shadow: 0 10px 15px 2px rgba(0, 0, 0, 0.1);
}
.body-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  opacity: 0.79;
  z-index: 10;
}
ul {
  padding: 0;
}
.header {
  padding-bottom: 17px;
}
p {
  font-size: 15px;
  color: #0dabf3;
  top: -42px;
  margin-top: -13px;
  font-family: cursive;
}
.list-group-item {
  padding: 0.75rem 1.25rem;
  border-bottom: 1px dashed rgba(169, 167, 167, 0.34) !important;
  border: none;
  color: #fff;
  font-size: 19px;
  font-weight: 300;
}
.btnTask {
  background: #0dabf3;
  margin-left: 5px;
}
.list-group,
.list-group-item {
  background: 0 0 !important;
}
.btnClear,
.btnClear:hover {
  color: #ffc107;
  float: right;
}
h1 {
  margin: 0;
  padding: 20px;
  color: #0dabf3;
}

Here’s what it looks like after updating css into your file:

Set up some variables for the web page elements like the form, the unordered list, the button, and the text input.

var inp = document.querySelector(".taskname");
var list = document.querySelector(".tasklist");
var addTask = document.querySelector(".btnTask");
var taskClear = document.querySelector(".btnClear");
var taskList = [];

Next, Make a function that creates an li element on the web page.

Ezoic

function render(elemments) {
  list.innerHTML = "";
  elemments.forEach(e => {
    let newEl = document.createElement("li");
    newEl.innerHTML = e;
    newEl.classList.add("list-group-item");
    list.appendChild(newEl);
  });
}

Add event listener to the form that watches for a click event, which will be any time you click add task button on the form. 

Call the render() function, which will create the item with the text of the input value and append it to the DOM using js push() method. Finally, we’ll set the input value to an empty string so you don’t have to erase the last item entered manually.

addTask.addEventListener("click", e => {
  if (inp.value !== "") {
    taskList.push(inp.value);
    inp.value = "";
    render(taskList);
    taskClear.style.display = "block";
    localStorage.setItem("mylist", JSON.stringify(taskList));
  } else {
    alert("Please input your task");
  }
});

Our taskList is being reset to an empty array every time the script runs. We could fix this by making a conditional statement that checks if localStorage already exists, such as in the below example.

let saved = localStorage.getItem("mylist");
if (saved) {
  taskList = JSON.parse(localStorage.getItem("mylist"));
  render(taskList);
} else {
  taskClear.style.display = "none";
}

Last, we’ll add a click event to the button that will clear all data from localStorage, as well as removing every child node from the ul.

Ezoic

taskClear.addEventListener("click", function() {
  localStorage.clear();
  list.innerHTML = "";
  taskList = [];
  taskClear.style.display = "none";
});

Update the javascript code into your scr/script.js file:

var inp = document.querySelector(".taskname");
var list = document.querySelector(".tasklist");
var addTask = document.querySelector(".btnTask");
var taskClear = document.querySelector(".btnClear");
var taskList = [];
function render(elemments) {
  list.innerHTML = "";
  elemments.forEach(e => {
    let newEl = document.createElement("li");
    newEl.innerHTML = e;
    newEl.classList.add("list-group-item");
    list.appendChild(newEl);
  });
}
addTask.addEventListener("click", e => {
  if (inp.value !== "") {
    taskList.push(inp.value);
    inp.value = "";
    render(taskList);
    taskClear.style.display = "block";
    localStorage.setItem("mylist", JSON.stringify(taskList));
  } else {
    alert("Please input your task");
  }
});
let saved = localStorage.getItem("mylist");
if (saved) {
  taskList = JSON.parse(localStorage.getItem("mylist"));
  render(taskList);
} else {
  taskClear.style.display = "none";
}
taskClear.addEventListener("click", function() {
  localStorage.clear();
  list.innerHTML = "";
  taskList = [];
  taskClear.style.display = "none";
});

Advantage and Disadvantage of localStorage

Advantages of localStorage

  • It stores up to 5-10MB of data (depending on the browser).
  • Easy to use – no need for a web server or backend database.
  • Great for getting an idea up and running and for testing purposes.

Disadvantages of localStorage

  • It only stores up to 10MB of data (5MB in some browsers).
  • It can only store strings. This can restrict you from using it for more complex scenarios; although, HTML can be stored as a string – more on that later…
  • It’s local to the browser and specific to the origin (per domain and protocol), and there’s no guarantee that the data will persist even in that same context.

Some of the frequently asked question about JavaScript localStroage:

1: How to get data from localstorage in javascript?

You can use localStroage.setItem() method.

Ezoic

2: How to remove or delete data from localStorage data in javascript?

You can use localStorage.getItem() method.

3: How to remove or delete data from localStorage data in javascript?

You can use localStorage.removeItem() method.

4: How to clear all localStorage data in javascript?

You can use localStorage.clear() method.

You can see the all localStorage method below, asked in the given question.

Recommended JavaScript Tutorials

Jaspreet Singh Ghuman

Jaspreet Singh Ghuman

Jassweb.com/

Passionate Professional Blogger, Freelancer, WordPress Enthusiast, Digital Marketer, Web Developer, Server Operator, Networking Expert. Empowering online presence with diverse skills.

jassweb logo

Jassweb always keeps its services up-to-date with the latest trends in the market, providing its customers all over the world with high-end and easily extensible internet, intranet, and extranet products.

Contact
San Vito Al Tagliamento 33078
Pordenone Italy
Item added to cart.
0 items - 0.00
Open chat
Scan the code
Hello 👋
Can we help you?