Local and Session storage

Local storage

// Set local storage item
localStorage.setItem('name', 'John');
localStorage.setItem('age', 30);

//get from storage
const name = localStorage.getItem('name');
const age = localStorage.getItem('age');
console.log(name, age);

// Remove from storage
localStorage.removeItem('name');

Session storage

// Set session storage item
sessionStorage.setItem('name', 'Jack');

Store array of data in local storage

Type data in a form, click on submit button and store it in the local storage of the browser.

document.querySelector('form').addEventListener('submit', function(e){
  const task = document.getElementById('task').value;

  //Initialize the tasks variable
  let tasks;

  if(localStorage.getItem('tasks') === null) {
    tasks = [];
  } else {
    tasks = JSON.parse(localStorage.getItem('tasks'));
  }

  tasks.push(task);

  localStorage.setItem('tasks', JSON.stringify(tasks));
  
  alert('Task saved');

  e.preventDefault();
});

Display data from local storage in the console

const tasks = JSON.parse(localStorage.getItem('tasks'));

tasks.forEach(function(task){
  console.log(task);
});
Was this page helpful?

Reader Interactions

Leave a Reply

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