Search Here

How to use localStorage in Javascript – Complete Guide with Examples

What is a Local Storage in Javascript

The Local Storage is an object belonging to Storage class which is available under the global window object. This is one of the ways of storing data locally with no expiration date.

Javascript window.localStorage object exposes some of the methods which can be used to access and modify data within.

Syntax

window.localStorage

Insert Data using setItem(key, value) method

The setItem() method is used to insert data into localStorage. It takes two parameters key and value.

window.localStorage.setItem("app_name", "The Code Learners");
The window.localStorage.setItem(key, value) method can also be used to update the existing save an item.

Fetch Data using getItem(key) method

The getItem() method is used to fetch data. It takes key as a parameter to get its value.

window.localStorage.getItem("app_name"); // The Code Learners

Remove Data using removeItem(key) method

The removeItem() method is used to fetch data. It takes key as a parameter that will remove the item from the localStorage.

window.localStorage.removeItem("app_name");

Clear All Data using clear() method

The clear() method is used to clear all the data present in localStorage.

window.localStorage.clear();

Get key name by passing index as parameter using key() method

The key(index) method will get the key name when index the number is passed.

window.localStorage.key(1); 
window.localStorage.key(2); 

Looping through all the keys

let exists = true;
let index = 0;
while(exists){
    let keyName = window.localStorage.key(index);
    if( keyName ){
        console.log("Key Name", keyName);
    } else {
        exists=false;
    }

    index++;
}

//ouput
Key Name app_name
Key Name name
It will return null if the index doesn’t exists in localStorage.

Practice Examples

Create a Todo App with Local Storage

<p>Entered Name is : <span id="name-placeholder" ></span></p>
<input type="text" id="name" value="" />
<hr />

<input type="button" onclick="getName()" value="Get Name" />
<input type="button" onclick="setName()" value="Set Name" />
<input type="button" onclick="setName()" value="Update Name" />
<input type="button" onclick="removeName()" value="Remove Name" />

<script>
    //The setName() with insert or update the name
    function setName(){
        window.localStorage.setItem("name", document.getElementById("name").value);
        getName(); //this will fetch the new name value again
    }

    function getName(){
        let name = window.localStorage.getItem("name"); // getting value by key name
        document.getElementById('name-placeholder').innerText = name
    }

    function removeName(){
        window.localStorage.removeItem("name")
        getName(); //this will fetch the new name value again
    }

    getName(); //Fetching the name on page load 
</script>

Uploading File in LocalStorage

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Multiple File Preview using createObjectURL method</title>
    <style>
        .img-small{
            width: 100px;
            height: auto;
        }

        #image-template{
            display: flex;
        }
    </style>
</head>
<body>
    <div id="image-template"></div>

    <input onchange="show_file_previews( event )" type="file" id="file" multiple  />

    <button type="button" onclick="getImage()" >Get Image</button>

    <script>
        let image_template = document.getElementById('image-template');
        
        let icons_url = {
            'xlsx' : 'https://img.icons8.com/color/48/000000/ms-excel.png',
            'pdf' : 'https://img.icons8.com/color/50/000000/pdf.png',
            'docx' : 'https://img.icons8.com/color/48/000000/word.png',
        };

        function get_extenstion( file ){
            return file.name.split( "." )[1];
        }

        function saveToLocalStorage(url){
            window.localStorage.setItem("url", url);
        }

        function removeImage(){
            window.localStorage.removeItem("url");
            getImage();
        }

        function getImage(){
            let object_url = window.localStorage.getItem("url");
            image_template.innerHTML = object_url ? `
            <img src="${object_url}" class="img-small" /> 
            <button type="button" onclick="removeImage()" >Remove Image</button>
            ` : "";

        }

        function show_file_previews( e ){
            let file_element = e.target;
            let files = e.target.files;
            let object_url = null, div = null, extension=null;

            image_template.innerHTML = "";
            if( files.length ){
                for( let index in files ){

                    if( files[index] instanceof File ){ 
                        object_url = ( icons_url[extension] )? icons_url[extension]:  URL.createObjectURL( files[index] );          
                        saveToLocalStorage(object_url);
                    }

                }
            }
        }
    </script>
</body>
</html>

Note:

You cannot directly upload a file in localStorage, The file must be generate as a link using URL.createObjectURL() method and that URL will be added.

Why use localStorage?

  • The localStorage is usually used to store metadata which is frequently accessed by the website.Such as Theme Switcher to switch between different theme colors.
  • Since the data saved within localStorage never expires the developer uses this to store general non-secure data which does not compromise the app security.

Limitations of using Local Storage

Some of the limitations of localStorage being aware are:

  • The Max Storage limit is less. Which is 5MB in Chrome Browser.
  • Unlike sessions and cookies, the data saved within localStorage never expires. Not even after the browser is closed.
  • Should not be used the store security-related data such as user login information and customer credit card information etc.

Check if your browser supports localStorage – Browser Compatibility

The window.localStorage is supported in most modern browsers.

Check if your browser supports

typeof Storage !== "undefined" // returns true if supports localStorage

Below mentioned old browsers versions don’t support localStorage

  • Internet Explorer Version 6-7
  • Firefox 2-3
  • Opera 10.1

Note

To learn more about browser compatibility of localStorage go to caniuse.com.

Watch Video