javascript save variable to local storage code example

Example 1: how to add variable to local storage in javascript

localStorage.setItem('key', 'value')

Example 2: js save local storage

//Set item
localStorage.setItem('myCat', 'Tom');
//Get item
var cat = localStorage.getItem("myCat");
//Remove item
localStorage.removeItem("lastname");
//Remove all items
localStorage.clear();

Example 3: javascript save data to local storage

// Store
localStorage.lastname = "Smith";
// Retrieve
document.getElementById("result").innerHTML = localStorage.lastname;
// Remove
localStorage.removeItem("lastname");

Example 4: how to get data from localstorage in javascript

//localStorage is an object, so values are stored by key name
//data from localStorage is always stored in strings
//usually the values at each key are stringified objects in JSON format, therefore we must parse them
var data = JSON.parse(localStorage.getItem("key name"));//make sure the "key name" exists in the localStorage