SessionStorage Basics

Store and retrieve data in sessionStorage

BeginnerTopic: LocalStorage/SessionStorage
Back

JavaScript SessionStorage Basics Program

This program helps you to learn the fundamental structure and syntax of JavaScript programming.

Try This Code
// Method 1: Set item
sessionStorage.setItem('sessionId', 'abc123');
sessionStorage.setItem('pageViews', '5');
sessionStorage.setItem('lastPage', '/home');

// Method 2: Get item
const sessionId = sessionStorage.getItem('sessionId');
console.log('Session ID:', sessionId);

// Method 3: Remove item
sessionStorage.removeItem('pageViews');

// Method 4: Clear all
// sessionStorage.clear();

// Method 5: Store object
const sessionData = {
    userId: 123,
    username: 'John',
    loginTime: new Date().toISOString()
};

sessionStorage.setItem('sessionData', JSON.stringify(sessionData));

const storedData = JSON.parse(sessionStorage.getItem('sessionData'));
console.log('Session Data:', storedData);

// Method 6: Update page views
let pageViews = parseInt(sessionStorage.getItem('pageViews') || '0');
pageViews++;
sessionStorage.setItem('pageViews', pageViews.toString());
console.log('Page views:', pageViews);

// Method 7: Track navigation
function trackPage(page) {
    const history = JSON.parse(sessionStorage.getItem('pageHistory') || '[]');
    history.push({
        page: page,
        timestamp: new Date().toISOString()
    });
    sessionStorage.setItem('pageHistory', JSON.stringify(history));
}

trackPage('/home');
trackPage('/about');
trackPage('/contact');

const history = JSON.parse(sessionStorage.getItem('pageHistory'));
console.log('Page history:', history);

// Method 8: Temporary form data
function saveFormData(formData) {
    sessionStorage.setItem('formData', JSON.stringify(formData));
}

function getFormData() {
    const data = sessionStorage.getItem('formData');
    return data ? JSON.parse(data) : null;
}

// Save form data
saveFormData({
    name: 'John',
    email: 'john@example.com',
    message: 'Hello'
});

// Retrieve form data
const formData = getFormData();
console.log('Form data:', formData);

// Method 9: Session timeout
function setSessionTimeout(minutes) {
    const expiry = new Date().getTime() + (minutes * 60 * 1000);
    sessionStorage.setItem('sessionExpiry', expiry.toString());
}

function isSessionValid() {
    const expiry = sessionStorage.getItem('sessionExpiry');
    if (!expiry) return false;
    
    return new Date().getTime() < parseInt(expiry);
}

setSessionTimeout(30); // 30 minutes
console.log('Session valid:', isSessionValid());

// Method 10: Clear on tab close
window.addEventListener('beforeunload', function() {
    // sessionStorage is automatically cleared when tab closes
    // But you can add cleanup code here
    console.log('Tab closing, sessionStorage will be cleared');
});
Output
Session ID: abc123
Session Data: { userId: 123, username: 'John', loginTime: '2024-01-01T12:00:00.000Z' }
Page views: 6
Page history: [
  { page: '/home', timestamp: '2024-01-01T12:00:00.000Z' },
  { page: '/about', timestamp: '2024-01-01T12:00:01.000Z' },
  { page: '/contact', timestamp: '2024-01-01T12:00:02.000Z' }
]
Form data: { name: 'John', email: 'john@example.com', message: 'Hello' }
Session valid: true

Understanding SessionStorage Basics

sessionStorage stores data for one session.

Key Differences from localStorage

Cleared when tab closes
Tab-specific (not shared)
Same API as localStorage
Temporary storage

Use Cases

Session data
Form data (temporary)
Page navigation tracking
Temporary user state

Methods

Same as localStorage
setItem/getItem/removeItem
clear/key/length

When to Use

Temporary data
Tab-specific data
Session tracking
Form recovery

Best Practices

Use for temporary data
Clear when done
Handle tab close
Check expiry if needed

Let us now understand every line and the components of the above program.

Note: To write and run JavaScript programs, you need to set up the local environment on your computer. Refer to the complete article Setting up JavaScript Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your JavaScript programs.

Practical Learning Notes for SessionStorage Basics

This JavaScript program is part of the "LocalStorage/SessionStorage" topic and is designed to help you build real problem-solving confidence, not just memorize syntax. Start by understanding the goal of the program in plain language, then trace the logic line by line with a custom input of your own. Once you can predict the output before running the code, your understanding becomes much stronger.

A reliable practice pattern is to run the original version first, then modify only one condition or variable at a time. Observe how that single change affects control flow and output. This deliberate style helps you understand loops, conditions, and data movement much faster than copying full solutions repeatedly.

For interview preparation, explain this solution in three layers: the high-level approach, the step-by-step execution, and the time-space tradeoff. If you can teach these three layers clearly, you are ready to solve close variations of this problem under time pressure.

Table of Contents