localStorage api code example

Example 1: save to local storage

localStorage.setItem('myCat', 'Tom');

var cat = localStorage.getItem('myCat');

localStorage.removeItem('myCat');

// Clear all items
localStorage.clear();

Example 2: localstorage js

// Set
localStorage.setItem('monChat', 'Tom');

// Get
localStorage.getItem('myCat');

// Remove
localStorage.removeItem('myCat');

Example 3: local storage

function setItem(name, value) {
  localStorage.setItem(name, value);
}
function getItem(name) {
  localStorage.getItem(name);
}
function deletItem(name) {
  localStorage.removeItem(name);
}
function clearStorage() {
  localStorage.clear();
}

Example 4: localStorage

// localStorage for objects, arrays or any data type
var obj = {
	firstName: "Bob",
    lastName: "Jeff",
    age: 13
}
localStorage.setItem("itemname", JSON.stringify(obj)); // Save the obj as string
var item = JSON.parse(localStorage.getItem("itemname")); 
// ^^ Parse string then set `item` as the obj

Example 5: localstorage

window.localStorage.setItem('myCat', 'Tom');
const cat = window.localStorage.getItem('myCat');

Example 6: localstorage

var cat = localStorage.getItem('myCat');