08-21-2022, 08:08 PM
JavaScript localStorage – Simple Guide with Example
<div style="margin: 5px 5% 10px 5%;"><img src="https://www.sickgaming.net/blog/wp-content/uploads/2022/08/javascript-localstorage-simple-guide-with-example.jpg" width="550" height="340" title="" alt="" /></div><div><div class="modified-on" readability="7.1111111111111"> by <a href="https://phppot.com/about/">Vincy</a>. Last modified on August 21st, 2022.</div>
<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>
<p>Data storage is a critical part of programming. These are the scenarios the localStorage used for adding persistency on the client-side.</p>
<ol>
<li>To store the session and the unique identity of a guest user to manage the state of his selection.</li>
<li>To store <a href="https://phppot.com/php/simple-php-shopping-cart/">shopping cart</a> selected items on the client-side.</li>
<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>
<li>To store user preferences to display data, time and timezone as selected on the client.</li>
</ol>
<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>
<div class="post-section-highlight" readability="36">
<h2>Quick example</h2>
<pre class="prettyprint"><code class="language-javascript">var animalObject = { 'Lion': 'Wild', 'Dog': 'Domestic'
}; // flatten the animal object as a string
animalString = JSON.stringify(animalObject); //store the string into local storage
localStorage.setItem('animals', animalString);
</code></pre>
</div>
<h3>Quick example output</h3>
<p>Log this localStorage object into the developer’s browser console to display the following output.</p>
<pre class="prettyprint"><code>Object from local storage: {Lion: 'Wild', Dog: 'Domestic'}
</code></pre>
<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>
<h2><img 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/20...00x186.jpg 300w, https://phppot.com/wp-content/uploads/20...68x475.jpg 768w, https://phppot.com/wp-content/uploads/20...object.jpg 1000w" sizes="(max-width: 550px) 100vw, 550px"></h2>
<h2>What is localStorage?</h2>
<p>The JavaScript localStorage is the global window object property. It is used to store the data to carry over page-to-page.</p>
<p>It is one of the storage mechanisms coming under the Web Storage API.</p>
<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>
<p>It contains a handle to access the local storage space of the browser origin.</p>
<h3>Properties</h3>
<h2>Web Storage API</h2>
<p>Web Storage API provides two concepts to store the objects having data in a key: value format.</p>
<ol>
<li>window.localStorage</li>
<li>window.sessionStorage</li>
</ol>
<p>Both use different Storage instances and control the actions separately.</p>
<p>This storage object is similar to the JavaScript localStorage. But, it has an expiration time.</p>
<p>It is valid only on the current browser session. When closing and reloading the browser, then the sessionStorage object is elapsed.</p>
<p>The expiration time is the main difference between these two storage concepts.</p>
<h2>How to set and get items in JavaScript localStorage?</h2>
<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>
<ol>
<li>To <strong>set</strong> an item as a key-value pair.</li>
<li>To <strong>get the value</strong> of an item by key.</li>
<li>To <strong>remove</strong> an item by key.</li>
<li>To <strong>clear</strong> the entire localStorage.</li>
<li>To <strong>get the key</strong> by item index position.</li>
</ol>
<p>This localStorage class contains functions used to perform the above actions. This program uses these functions with appropriate parameters.</p>
<p class="code-heading">basics.html</p>
<pre class="prettyprint"><code class="language-php-template"><html>
<head>
<title>JavaScript localStorage Example and how to store a JavaScript object</title>
</head>
<body> <script> // 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(); </script>
</body>
</html>
</code></pre>
<p><strong>Output</strong></p>
<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’s key and value based on the appropriate function calls.</p>
<pre class="prettyprint"><code>Local Storage Key-Value = {"king":"Lion"} Local Storage Value = Lion Local Storage Key = king
</code></pre>
<h2>Store JavaScript object in HTML5 browser localStorage</h2>
<p>This example is to store an object in the JavaScript localStorage. It proceeds with the following steps to achieve this.</p>
<ol>
<li>It builds a JSON object to have a property array.</li>
<li>It converts the object into a string using JSON stringify.</li>
<li>Then put the JSON string into the localStorage.</li>
</ol>
<p>Like the above basic example, it calls the getItem() by object key to get the property mapping.</p>
<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>
<p class="code-heading">index.html</p>
<pre class="prettyprint"><code class="language-php-template"><html>
<head>
<title>JavaScript localStorage Example and how to store a JavaScript object</title>
</head>
<body> <h1>JavaScript localStorage Example and how to store a JavaScript object</h1> <script> // 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); </script>
</body>
</html>
</code></pre>
<h3>Output</h3>
<pre class="prettyprint"><code>Object from local storage: {Lion: 'Wild', Dog: 'Domestic', Tiger: 'Wild'}
</code></pre>
<p>We learned how to use JavaScript localStorage to set a String or an Object and use it later when needed.</p>
<p> <!-- #comments --> </p>
<p> <a href="https://phppot.com/javascript/javascript-localstorage/#top" class="top">↑ Back to Top</a> </p>
</div>
https://www.sickgaming.net/blog/2022/08/...h-example/
<div style="margin: 5px 5% 10px 5%;"><img src="https://www.sickgaming.net/blog/wp-content/uploads/2022/08/javascript-localstorage-simple-guide-with-example.jpg" width="550" height="340" title="" alt="" /></div><div><div class="modified-on" readability="7.1111111111111"> by <a href="https://phppot.com/about/">Vincy</a>. Last modified on August 21st, 2022.</div>
<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>
<p>Data storage is a critical part of programming. These are the scenarios the localStorage used for adding persistency on the client-side.</p>
<ol>
<li>To store the session and the unique identity of a guest user to manage the state of his selection.</li>
<li>To store <a href="https://phppot.com/php/simple-php-shopping-cart/">shopping cart</a> selected items on the client-side.</li>
<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>
<li>To store user preferences to display data, time and timezone as selected on the client.</li>
</ol>
<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>
<div class="post-section-highlight" readability="36">
<h2>Quick example</h2>
<pre class="prettyprint"><code class="language-javascript">var animalObject = { 'Lion': 'Wild', 'Dog': 'Domestic'
}; // flatten the animal object as a string
animalString = JSON.stringify(animalObject); //store the string into local storage
localStorage.setItem('animals', animalString);
</code></pre>
</div>
<h3>Quick example output</h3>
<p>Log this localStorage object into the developer’s browser console to display the following output.</p>
<pre class="prettyprint"><code>Object from local storage: {Lion: 'Wild', Dog: 'Domestic'}
</code></pre>
<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>
<h2><img 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/20...00x186.jpg 300w, https://phppot.com/wp-content/uploads/20...68x475.jpg 768w, https://phppot.com/wp-content/uploads/20...object.jpg 1000w" sizes="(max-width: 550px) 100vw, 550px"></h2>
<h2>What is localStorage?</h2>
<p>The JavaScript localStorage is the global window object property. It is used to store the data to carry over page-to-page.</p>
<p>It is one of the storage mechanisms coming under the Web Storage API.</p>
<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>
<p>It contains a handle to access the local storage space of the browser origin.</p>
<h3>Properties</h3>
<h2>Web Storage API</h2>
<p>Web Storage API provides two concepts to store the objects having data in a key: value format.</p>
<ol>
<li>window.localStorage</li>
<li>window.sessionStorage</li>
</ol>
<p>Both use different Storage instances and control the actions separately.</p>
<p>This storage object is similar to the JavaScript localStorage. But, it has an expiration time.</p>
<p>It is valid only on the current browser session. When closing and reloading the browser, then the sessionStorage object is elapsed.</p>
<p>The expiration time is the main difference between these two storage concepts.</p>
<h2>How to set and get items in JavaScript localStorage?</h2>
<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>
<ol>
<li>To <strong>set</strong> an item as a key-value pair.</li>
<li>To <strong>get the value</strong> of an item by key.</li>
<li>To <strong>remove</strong> an item by key.</li>
<li>To <strong>clear</strong> the entire localStorage.</li>
<li>To <strong>get the key</strong> by item index position.</li>
</ol>
<p>This localStorage class contains functions used to perform the above actions. This program uses these functions with appropriate parameters.</p>
<p class="code-heading">basics.html</p>
<pre class="prettyprint"><code class="language-php-template"><html>
<head>
<title>JavaScript localStorage Example and how to store a JavaScript object</title>
</head>
<body> <script> // 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(); </script>
</body>
</html>
</code></pre>
<p><strong>Output</strong></p>
<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’s key and value based on the appropriate function calls.</p>
<pre class="prettyprint"><code>Local Storage Key-Value = {"king":"Lion"} Local Storage Value = Lion Local Storage Key = king
</code></pre>
<h2>Store JavaScript object in HTML5 browser localStorage</h2>
<p>This example is to store an object in the JavaScript localStorage. It proceeds with the following steps to achieve this.</p>
<ol>
<li>It builds a JSON object to have a property array.</li>
<li>It converts the object into a string using JSON stringify.</li>
<li>Then put the JSON string into the localStorage.</li>
</ol>
<p>Like the above basic example, it calls the getItem() by object key to get the property mapping.</p>
<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>
<p class="code-heading">index.html</p>
<pre class="prettyprint"><code class="language-php-template"><html>
<head>
<title>JavaScript localStorage Example and how to store a JavaScript object</title>
</head>
<body> <h1>JavaScript localStorage Example and how to store a JavaScript object</h1> <script> // 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); </script>
</body>
</html>
</code></pre>
<h3>Output</h3>
<pre class="prettyprint"><code>Object from local storage: {Lion: 'Wild', Dog: 'Domestic', Tiger: 'Wild'}
</code></pre>
<p>We learned how to use JavaScript localStorage to set a String or an Object and use it later when needed.</p>
<p> <!-- #comments --> </p>
<p> <a href="https://phppot.com/javascript/javascript-localstorage/#top" class="top">↑ Back to Top</a> </p>
</div>
https://www.sickgaming.net/blog/2022/08/...h-example/