JavaScript Local Storage and Session Storage Practice Questions

Introductions

Web browsers provide Web Storage APIs that allow JavaScript to store small amounts of data directly in the user’s browser. The two main options are localStorage and sessionStorage.

In this chapter, you will practice storing data, retrieving data, updating values, deleting data, clearing storage, working with numbers and objects, and understanding the difference between localStorage and sessionStorage. JavaScript Local Storage and session storage practice questions with solutions help to understand the concepts.

Question 1: Store Data Using localStorage

Problem

Store a user’s name in localStorage and check the stored value.

Solution

localStorage.setItem("username", "Rahul");

console.log(localStorage.getItem("username"));

Output

Rahul

Step-by-step Explanation

  1. localStorage provides browser storage.
  2. setItem() stores data.
  3. "username" is the key.
  4. "Rahul" is the value.
  5. getItem() retrieves the stored value.

The basic syntax is:

localStorage.setItem("key", "value");

To retrieve it:

localStorage.getItem("key");

Question 2: Store and Retrieve Multiple Values

Problem

Store a user’s name and email in localStorage, then retrieve both values.

Solution

localStorage.setItem("name", "Aman");
localStorage.setItem("email", "aman@example.com");

const name = localStorage.getItem("name");
const email = localStorage.getItem("email");

console.log(name);
console.log(email);

Output

Aman
aman@example.com

Step-by-step Explanation

Two separate key-value pairs are stored:

name  → Aman
email → aman@example.com

Each value can be retrieved using its key.

localStorage.getItem("name");
localStorage.getItem("email");

Question 3: Update an Existing localStorage Value

Problem

Store a user’s theme as "light", then change it to "dark".

Solution

localStorage.setItem("theme", "light");

console.log(localStorage.getItem("theme"));

localStorage.setItem("theme", "dark");

console.log(localStorage.getItem("theme"));

Output

light
dark

Step-by-step Explanation

If the same key already exists, calling setItem() again replaces its value.

First:

localStorage.setItem("theme", "light");

Then:

localStorage.setItem("theme", "dark");

The value associated with "theme" is now "dark".


Question 4: Remove One Item from localStorage

Problem

Store a username and email, then remove only the username.

Solution

localStorage.setItem("username", "Priya");
localStorage.setItem("email", "priya@example.com");

localStorage.removeItem("username");

console.log(localStorage.getItem("username"));
console.log(localStorage.getItem("email"));

Output

null
priya@example.com

Step-by-step Explanation

removeItem() deletes a specific key:

localStorage.removeItem("username");

The email remains because it uses a different key.

When getItem() cannot find a key, it returns:

null

Question 5: Clear All localStorage Data

Problem

Store three values and then remove all stored values.

Solution

localStorage.setItem("name", "Rahul");
localStorage.setItem("age", "20");
localStorage.setItem("course", "JavaScript");

localStorage.clear();

console.log(localStorage.getItem("name"));
console.log(localStorage.getItem("age"));
console.log(localStorage.getItem("course"));

Output

null
null
null

Step-by-step Explanation

localStorage.clear() removes all key-value pairs from the local storage area for the current website’s origin.

localStorage.clear();

Use this carefully because it removes everything stored there for that origin, not just one particular key.


Question 6: Store a Number in localStorage

Problem

Store a user’s age in localStorage, retrieve it, and add 5 to it.

Solution

localStorage.setItem("age", 20);

const age = Number(localStorage.getItem("age"));

console.log(age + 5);

Output

25

Step-by-step Explanation

Web Storage stores values as strings.

Even though we write:

localStorage.setItem("age", 20);

the stored value is retrieved as text.

So it is a good idea to convert it back into a number:

Number(localStorage.getItem("age"));

Now arithmetic can be performed correctly.


Question 7: Store an Object Using JSON

Problem

Store a JavaScript user object in localStorage and retrieve it as an object again.

Solution

const user = {
    name: "Aman",
    age: 19,
    course: "JavaScript"
};

localStorage.setItem("user", JSON.stringify(user));

const storedUser = JSON.parse(
    localStorage.getItem("user")
);

console.log(storedUser.name);
console.log(storedUser.course);

Output

Aman
JavaScript

Step-by-step Explanation

Web Storage stores strings, so you cannot directly store a JavaScript object and expect it to come back as an object.

First convert the object into JSON:

JSON.stringify(user);

Store it:

localStorage.setItem("user", JSON.stringify(user));

Retrieve it:

localStorage.getItem("user");

Then convert the JSON string back into an object:

JSON.parse(localStorage.getItem("user"));

The complete process is:

JavaScript Object
       ↓
JSON.stringify()
       ↓
JSON String
       ↓
localStorage
       ↓
JSON.parse()
       ↓
JavaScript Object

Question 8: Use sessionStorage

Problem

Store a username using sessionStorage and retrieve it.

Solution

sessionStorage.setItem("username", "Riya");

const username = sessionStorage.getItem("username");

console.log(username);

Output

Riya

Step-by-step Explanation

sessionStorage uses methods similar to localStorage.

Store data:

sessionStorage.setItem("key", "value");

Retrieve data:

sessionStorage.getItem("key");

The main difference is how long the data is retained.

  • localStorage persists across browser sessions until the stored data is removed.
  • sessionStorage is associated with the current browser tab/session and is cleared when that tab or window is closed.

Question 9: Create a Simple Dark Mode Preference

Problem

Create a simple dark mode button. Save the user’s selected theme in localStorage.

Solution

<button id="themeButton">
    Dark Mode
</button>

<script>
const button = document.getElementById("themeButton");

button.addEventListener("click", function() {

    document.body.style.backgroundColor = "black";
    document.body.style.color = "white";

    localStorage.setItem("theme", "dark");

});
</script>

Output

When the button is clicked:

  • The page background becomes black.
  • The text becomes white.
  • "dark" is saved in localStorage.

Step-by-step Explanation

When the button is clicked:

document.body.style.backgroundColor = "black";

changes the background.

Then:

document.body.style.color = "white";

changes the text color.

Finally:

localStorage.setItem("theme", "dark");

remembers the user’s selected theme.

This is a practical example of using browser storage to remember a preference.


Question 10: Build a Simple LocalStorage To-Do List

Problem

Create a small to-do list that saves tasks in localStorage. When the page loads, previously saved tasks should be displayed.

Solution

<input type="text" id="taskInput" placeholder="Enter a task">

<button id="addButton">
    Add Task
</button>

<ul id="taskList"></ul>

<script>
const input = document.getElementById("taskInput");
const button = document.getElementById("addButton");
const list = document.getElementById("taskList");

let tasks = JSON.parse(
    localStorage.getItem("tasks")
) || [];

function displayTasks() {

    list.innerHTML = "";

    tasks.forEach(function(task) {

        const li = document.createElement("li");

        li.textContent = task;

        list.appendChild(li);

    });
}

button.addEventListener("click", function() {

    const task = input.value.trim();

    if (task === "") {
        return;
    }

    tasks.push(task);

    localStorage.setItem(
        "tasks",
        JSON.stringify(tasks)
    );

    input.value = "";

    displayTasks();

});

displayTasks();
</script>

Output

If the user adds:

Learn JavaScript
Practice DOM
Learn Fetch API

the webpage displays:

Learn JavaScript
Practice DOM
Learn Fetch API

If the page is refreshed, the saved tasks can still be loaded from localStorage.

Step-by-step Explanation

First, previously saved tasks are retrieved:

let tasks = JSON.parse(
    localStorage.getItem("tasks")
) || [];

If there are no saved tasks, an empty array is used:

[]

When the user adds a task:

tasks.push(task);

The new task is added to the array.

Then the array is converted into JSON:

JSON.stringify(tasks)

and saved:

localStorage.setItem(
    "tasks",
    JSON.stringify(tasks)
);

Finally, displayTasks() updates the webpage.

This example combines:

DOM
+
Events
+
Arrays
+
JSON
+
localStorage

Key Takeaways

  • localStorage stores data in the browser.
  • sessionStorage also stores browser data but is associated with the current page session.
  • Both APIs use key-value pairs.
  • setItem() stores or updates data.
  • getItem() retrieves data.
  • removeItem() removes one item.
  • clear() removes all items from that storage area for the current origin.
  • Web Storage values are stored as strings.
  • Use Number() when a stored numeric value needs to be used for arithmetic.
  • Use JSON.stringify() to store objects or arrays.
  • Use JSON.parse() to convert stored JSON back into JavaScript data.
  • localStorage is useful for preferences, simple settings, and small client-side data.
  • sessionStorage is useful for data that should remain available during the current tab/session.
  • Web Storage should not be treated as a secure place for passwords or sensitive information.
  • Storage availability and limits can vary by browser and environment.

FAQs

1. What is localStorage in JavaScript?

localStorage is a Web Storage API that allows a website to store string key-value pairs in the browser.

Example:

localStorage.setItem("name", "Rahul");

The value can later be retrieved with:

localStorage.getItem("name");

2. What is sessionStorage?

sessionStorage is another Web Storage API.

Example:

sessionStorage.setItem("username", "Aman");

Its data is associated with the current browsing session and is generally removed when that tab or window is closed.

3. What is the difference between localStorage and sessionStorage?

The main difference is persistence.

FeaturelocalStoragesessionStorage
Stores key-value dataYesYes
Values stored as stringsYesYes
Survives page refreshYesYes
Persists after closing the tabGenerally yesNo
setItem()YesYes
getItem()YesYes
removeItem()YesYes
clear()YesYes

4. Can localStorage store JavaScript objects directly?

No. Web Storage stores strings.

Convert an object to JSON first:

const user = {
    name: "Rahul",
    age: 20
};

localStorage.setItem(
    "user",
    JSON.stringify(user)
);

Retrieve it with:

const user = JSON.parse(
    localStorage.getItem("user")
);

5. What does getItem() return when a key does not exist?

getItem() returns null when the requested key does not exist.

const value = localStorage.getItem("unknown");

console.log(value);

Output:

null

6. How do you delete localStorage data?

To delete one item:

localStorage.removeItem("username");

To remove all items from the local storage area for the current origin:

localStorage.clear();

Use clear() carefully because it removes all stored items in that storage area.

7. Is localStorage safe for passwords?

No. Do not use localStorage or sessionStorage as a secure storage mechanism for passwords, authentication secrets, or other sensitive information.

JavaScript running on the page can access Web Storage, so storing sensitive secrets there can create security risks.

Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.

Scroll to Top