sessionStorage javascript code example

Example 1: how to set session storage in javascript

// Save data to sessionStorage
sessionStorage.setItem('key', 'value');

// Get saved data from sessionStorage
let data = sessionStorage.getItem('key');

// Remove saved data from sessionStorage
sessionStorage.removeItem('key');

// Remove all saved data from sessionStorage
sessionStorage.clear();

Example 2: javascript hasownproperty

var person = {	
  	"first_name": "Bob",
	"last_name": "Dylan"
};
person.hasOwnProperty('first_name'); //returns true
person.hasOwnProperty('age'); //returns false

Example 3: local storage javascript

localStorage.setItem('user_name', 'Rohit'); //store a key/value
var retrievedUsername = localStorage.getItem('user_name'); //retrieve the key

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: javascript sessionStorage

var setsession = window.sessionStorage.setItem("animals", "cat");
	var getsession = window.sessionStorage.getItem("animals");
	console.log(getsession);

Example 6: what is local storage and session storage in javascript

//localStorage - stores data with no expiration date. window. sessionStorage - stores data for one session (data is lost when the browser tab is closed)