{"id":127445,"date":"2022-08-21T10:35:27","date_gmt":"2022-08-21T10:35:27","guid":{"rendered":"https:\/\/phppot.com\/?p=18992"},"modified":"2022-08-21T10:35:27","modified_gmt":"2022-08-21T10:35:27","slug":"javascript-localstorage-simple-guide-with-example","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2022\/08\/21\/javascript-localstorage-simple-guide-with-example\/","title":{"rendered":"JavaScript localStorage \u2013 Simple Guide with Example"},"content":{"rendered":"<div class=\"modified-on\" readability=\"7.1111111111111\"> by <a href=\"https:\/\/phppot.com\/about\/\">Vincy<\/a>. Last modified on August 21st, 2022.<\/div>\n<p>This article is for learning <strong>how to use JavaScript localStorage to put a string or object into it<\/strong>. This is for storing data in the client browser and use it when the need arises.<\/p>\n<p>Data storage is a critical part of programming. These are the scenarios the localStorage used for adding persistency on the client-side.<\/p>\n<ol>\n<li>To store the session and the unique identity of a guest user to manage the state of his selection.<\/li>\n<li>To store <a href=\"https:\/\/phppot.com\/php\/simple-php-shopping-cart\/\">shopping cart<\/a> selected items on the client-side.<\/li>\n<li>To store language preferences to display content on a <a href=\"https:\/\/phppot.com\/wordpress\/creating-multilingual-wordpress-site-using-google-language-translator\/\">multilingual site<\/a>.<\/li>\n<li>To store user preferences to display data, time and timezone as selected on the client.<\/li>\n<\/ol>\n<p>Let us see a quick example of using the JavaScript localStorage to store an object. It prepares a JSON object of an array of data and put it into the localStorage.<\/p>\n<div class=\"post-section-highlight\" readability=\"36\">\n<h2>Quick example<\/h2>\n<pre class=\"prettyprint\"><code class=\"language-javascript\">var animalObject = { 'Lion': 'Wild', 'Dog': 'Domestic'\n}; \/\/ flatten the animal object as a string\nanimalString = JSON.stringify(animalObject); \/\/store the string into local storage\nlocalStorage.setItem('animals', animalString);\n<\/code><\/pre>\n<\/div>\n<h3>Quick example output<\/h3>\n<p>Log this localStorage object into the developer\u2019s browser console to display the following output.<\/p>\n<pre class=\"prettyprint\"><code>Object from local storage: {Lion: 'Wild', Dog: 'Domestic'}\n<\/code><\/pre>\n<p>In a previous tutorial, we used JavaScript localStorage to create a <a href=\"https:\/\/phppot.com\/javascript\/javascript-shopping-cart\/\">persistent shopping cart<\/a>.<\/p>\n<h2><img decoding=\"async\" loading=\"lazy\" class=\"alignnone size-large wp-image-19003\" src=\"https:\/\/phppot.com\/wp-content\/uploads\/2022\/08\/javascript-localstorage-howto-store-object-550x340.jpg\" alt=\"javascript localstorage howto store object\" width=\"550\" height=\"340\" srcset=\"https:\/\/phppot.com\/wp-content\/uploads\/2022\/08\/javascript-localstorage-howto-store-object-550x340.jpg 550w, https:\/\/phppot.com\/wp-content\/uploads\/2022\/08\/javascript-localstorage-howto-store-object-300x186.jpg 300w, https:\/\/phppot.com\/wp-content\/uploads\/2022\/08\/javascript-localstorage-howto-store-object-768x475.jpg 768w, https:\/\/phppot.com\/wp-content\/uploads\/2022\/08\/javascript-localstorage-howto-store-object.jpg 1000w\" sizes=\"auto, (max-width: 550px) 100vw, 550px\"><\/h2>\n<h2>What is localStorage?<\/h2>\n<p>The JavaScript localStorage is the global window object property. It is used to store the data to carry over page-to-page.<\/p>\n<p>It is one of the storage mechanisms coming under the Web Storage API.<\/p>\n<p>It can not replace the <a href=\"https:\/\/phppot.com\/php\/how-to-build-a-persistent-shopping-cart-in-php\/\">server-side solutions providing persistency<\/a>. But, it is a good mechanism for non-dynamic websites.<\/p>\n<p>It contains a handle to access the local storage space of the browser origin.<\/p>\n<h3>Properties<\/h3>\n<h2>Web Storage API<\/h2>\n<p>Web Storage API provides two concepts to store the objects having data in a key: value format.<\/p>\n<ol>\n<li>window.localStorage<\/li>\n<li>window.sessionStorage<\/li>\n<\/ol>\n<p>Both use different Storage instances and control the actions separately.<\/p>\n<p>This storage object is similar to the JavaScript localStorage. But, it has an expiration time.<\/p>\n<p>It is valid only on the current browser session. When closing and reloading the browser, then the sessionStorage object is elapsed.<\/p>\n<p>The expiration time is the main difference between these two storage concepts.<\/p>\n<h2>How to set and get items in JavaScript localStorage?<\/h2>\n<p>This example is for learning a basic usage of the JavaScript localStorage object. It performs the following actions on the localStorage about a <em>String<\/em> item.<\/p>\n<ol>\n<li>To <strong>set<\/strong> an item as a key-value pair.<\/li>\n<li>To <strong>get the value<\/strong> of an item by key.<\/li>\n<li>To <strong>remove<\/strong> an item by key.<\/li>\n<li>To <strong>clear<\/strong> the entire localStorage.<\/li>\n<li>To <strong>get the key<\/strong> by item index position.<\/li>\n<\/ol>\n<p>This localStorage class contains functions used to perform the above actions. This program uses these functions with appropriate parameters.<\/p>\n<p class=\"code-heading\">basics.html<\/p>\n<pre class=\"prettyprint\"><code class=\"language-php-template\">&lt;html&gt;\n&lt;head&gt;\n&lt;title&gt;JavaScript localStorage Example and how to store a JavaScript object&lt;\/title&gt;\n&lt;\/head&gt;\n&lt;body&gt; &lt;script&gt; \/\/ set item in localstorage window.localStorage.setItem('king', 'Lion'); console.log(\"Local Storage Key-Value = \" + JSON.stringify(window.localStorage) + \"\\n\"); \/\/ get item from JavaScript localStorage window.localStorage.getItem('king'); console.log(\"Local Storage Value = \" + window.localStorage.getItem('king') + \"\\n\"); \/\/ to get name of key using index var indexPosition = parseInt(window.localStorage.length) -1; var KeyName = window.localStorage.key(indexPosition); console.log(\"Local Storage Key = \" + KeyName + \"\\n\"); \/\/ remove item from JavaScript localStorage window.localStorage.removeItem('king'); \/\/ to clear all items from localStorage window.localStorage.clear(); &lt;\/script&gt;\n&lt;\/body&gt;\n&lt;\/html&gt;\n<\/code><\/pre>\n<p><strong>Output<\/strong><\/p>\n<p>The above program displays the following output. It is for <a href=\"https:\/\/phppot.com\/php\/php-print-statements\/\">printing<\/a> the localStorage data, it\u2019s key and value based on the appropriate function calls.<\/p>\n<pre class=\"prettyprint\"><code>Local Storage Key-Value = {\"king\":\"Lion\"} Local Storage Value = Lion Local Storage Key = king\n<\/code><\/pre>\n<h2>Store JavaScript object in HTML5 browser localStorage<\/h2>\n<p>This example is to store an object in the JavaScript localStorage. It proceeds with the following steps to achieve this.<\/p>\n<ol>\n<li>It builds a JSON object to have a property array.<\/li>\n<li>It converts the object into a string using JSON stringify.<\/li>\n<li>Then put the JSON string into the localStorage.<\/li>\n<\/ol>\n<p>Like the above basic example, it calls the getItem() by object key to get the property mapping.<\/p>\n<p>The retrieved string output from the localStorage is converted back to an object. The example outputs the converted object to the browser console.<\/p>\n<p class=\"code-heading\">index.html<\/p>\n<pre class=\"prettyprint\"><code class=\"language-php-template\">&lt;html&gt;\n&lt;head&gt;\n&lt;title&gt;JavaScript localStorage Example and how to store a JavaScript object&lt;\/title&gt;\n&lt;\/head&gt;\n&lt;body&gt; &lt;h1&gt;JavaScript localStorage Example and how to store a JavaScript object&lt;\/h1&gt; &lt;script&gt; \/\/ Example: Store JavaScript object in HTML5 browser localStorage var animalObject = { 'Lion' : 'Wild', 'Dog' : 'Domestic', 'Tiger' : 'Wild' }; \/\/ flatten the object as a string animalString = JSON.stringify(animalObject); \/\/store the string into local storage localStorage.setItem('animals', animalString); \/\/retrieve the string from local storage var retrievedString = localStorage.getItem('animals'); \/\/ parse the string back to an object convertedObject = JSON.parse(retrievedString); console.log('Object from local storage: ', convertedObject); &lt;\/script&gt;\n&lt;\/body&gt;\n&lt;\/html&gt;\n<\/code><\/pre>\n<h3>Output<\/h3>\n<pre class=\"prettyprint\"><code>Object from local storage: {Lion: 'Wild', Dog: 'Domestic', Tiger: 'Wild'}\n<\/code><\/pre>\n<p>We learned how to use JavaScript localStorage to set a String or an Object and use it later when needed.<\/p>\n<p> <!-- #comments --> <\/p>\n<p> <a href=\"https:\/\/phppot.com\/javascript\/javascript-localstorage\/#top\" class=\"top\">\u2191 Back to Top<\/a> <\/p>\n","protected":false},"excerpt":{"rendered":"<p>by Vincy. Last modified on August 21st, 2022. This article is for learning how to use JavaScript localStorage to put a string or object into it. This is for storing data in the client browser and use it when the need arises. Data storage is a critical part of programming. These are the scenarios the [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":127446,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[65],"tags":[],"class_list":["post-127445","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-php-updates"],"_links":{"self":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/127445","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/comments?post=127445"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/127445\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media\/127446"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=127445"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=127445"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=127445"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}