LocalStorage Basics

Store and retrieve data in localStorage

BeginnerTopic: LocalStorage/SessionStorage
Back

JavaScript LocalStorage Basics Program

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

Try This Code
// Method 1: Set item
localStorage.setItem('username', 'John');
localStorage.setItem('age', '30');
localStorage.setItem('isLoggedIn', 'true');

// Method 2: Get item
const username = localStorage.getItem('username');
console.log('Username:', username); // "John"

const age = localStorage.getItem('age');
console.log('Age:', age); // "30" (string)

// Method 3: Remove item
localStorage.removeItem('age');

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

// Method 5: Check if key exists
if (localStorage.getItem('username')) {
    console.log('Username exists');
}

// Method 6: Get all keys
const keys = Object.keys(localStorage);
console.log('All keys:', keys);

// Method 7: Get all items
for (let i = 0; i < localStorage.length; i++) {
    const key = localStorage.key(i);
    const value = localStorage.getItem(key);
    console.log(key + ':', value);
}

// Method 8: Store object (stringify)
const user = {
    name: 'John',
    age: 30,
    email: 'john@example.com'
};

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

// Retrieve object (parse)
const storedUser = JSON.parse(localStorage.getItem('user'));
console.log('User:', storedUser);

// Method 9: Store array
const items = ['apple', 'banana', 'orange'];
localStorage.setItem('items', JSON.stringify(items));

const storedItems = JSON.parse(localStorage.getItem('items'));
console.log('Items:', storedItems);

// Method 10: Check storage availability
function isLocalStorageAvailable() {
    try {
        const test = '__localStorage_test__';
        localStorage.setItem(test, test);
        localStorage.removeItem(test);
        return true;
    } catch (e) {
        return false;
    }
}

if (isLocalStorageAvailable()) {
    console.log('LocalStorage is available');
} else {
    console.log('LocalStorage is not available');
}
Output
Username: John
Age: 30
Username exists
All keys: ["username", "age", "isLoggedIn"]
username: John
age: 30
isLoggedIn: true
User: { name: 'John', age: 30, email: 'john@example.com' }
Items: ["apple", "banana", "orange"]
LocalStorage is available

Understanding LocalStorage Basics

localStorage persists data across sessions.

Methods

setItem(key, value): Store data
getItem(key): Retrieve data
removeItem(key): Remove item
clear(): Remove all
key(index): Get key at index
length: Number of items

Important Notes

Stores strings only
Use JSON.stringify/parse for objects
Persists until cleared
Domain-specific
~5-10MB limit

Use Cases

User preferences
Shopping cart
Form data
Cache data

Best Practices

Check availability
Handle errors
Use try-catch
Validate data

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 LocalStorage 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