CodeBlanks Logo Icon CodeBlanks

sessionStorage

JavaScript course · Intermediate · Lesson 44/134

Learn to store tab-scoped temporary data with sessionStorage.

What is sessionStorage?

sessionStorage is a storage tool that offers the same methods as localStorage. The difference is that data is valid only for one tab. When you close the tab, everything inside is cleared.

sessionStorage.setItem('draft', 'hello');

Even if two tabs open the same site, each has its own sessionStorage; they cannot see each other's data. For persistent data, use localStorage.

The same four methods

sessionStorage shares the same four methods as localStorage: setItem, getItem, removeItem and clear. Everything you learned applies here the same way; you only change the keyword.

const draft = sessionStorage.getItem('draft');
sessionStorage.removeItem('draft');

The only difference between the two stores is lifetime. sessionStorage lives while the tab is open and vanishes when it closes; localStorage survives even if the browser is closed.

Exercise Save and read a temporary draft

Save the value 'hello' under the 'draft' key with sessionStorage.setItem. Then read it back into a draft variable with getItem.

Show example solution
sessionStorage.setItem('draft', 'hello');
const draft = sessionStorage.getItem('draft');

Test yourself

  1. What is the main difference between sessionStorage and localStorage?

    sessionStorage.setItem('x', '1');
    localStorage.setItem('x', '1');
    • sessionStorage is faster
    • sessionStorage stores only text
    • sessionStorage clears when the tab closes
    • sessionStorage holds less data
    Show answer

    sessionStorage clears when the tab closes — Correct! sessionStorage deletes data when the tab closes.

  2. Save a value to sessionStorage

    sessionStorage.____('draft', 'hello');
    Show answer
    sessionStorage.setItem('draft', 'hello');
  3. Match the properties

    localStorage
    Survives browser restart
    sessionStorage
    Cleared when tab closes
    Both
    Store only text
  4. You saved data to sessionStorage and closed the tab. What happens to the data?

    sessionStorage.setItem('token', 'abc');
    // tab closed
    • It returns when you reopen the browser
    • It is permanently deleted
    • It moves to localStorage
    • It is sent to the server
    Show answer

    It is permanently deleted — Correct! sessionStorage is permanently deleted when the tab closes.

All lessons in Intermediate