Skip to content

Instantly share code, notes, and snippets.

@Atefnouri
Last active April 9, 2019 16:07
Show Gist options
  • Save Atefnouri/f1b857e9cbc7b1c3e09717f3bfcd60cc to your computer and use it in GitHub Desktop.
Save Atefnouri/f1b857e9cbc7b1c3e09717f3bfcd60cc to your computer and use it in GitHub Desktop.
Local Storage in JavaScript
/*
localStorage and sessionStorage accomplish the exact same thing
and have the same API, but with sessionStorage the data is persisted
only until the window or tab is closed,while with localStorage the data is persisted
until the user manually clears the browser cache or until your web app clears the data.
The examples in this post are for localStorage, but the same syntax works for sessionStorage.
*/
//creat entery
let key = 'Item 1';
localStorage.setItem(key, 'Value');
// read
let myItem = localStorage.getItem(key);
//update
localStorage.setItem(key, 'New Value');
//Deleting
localStorage.removeItem(key);
//Clear evreything
localStorage.clear();
//Store & read Json Objetc
// Create item:
let myObj = { name: 'Skip', breed: 'Labrador' };
localStorage.setItem(key, JSON.stringify(myObj));
// Read item:
let item = JSON.parse(localStorage.getItem(key));
//Test for existance
if (localStorage.length > 0) {
// We have items
} else {
// No items
}
//Check for browser support
if (window.localStorage) {
// localStorage supported
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment