JavaScript Local Storage

Local storage is a web storage API that allows developers to store data in a web browser.

Unlike cookies, which are sent with every HTTP request, local storage is designed for storing larger amounts of data client-side without affecting the server.

Data stored in local storage persists even after the browser is closed, making it ideal for saving user preferences, session data, and other information that needs to be retained between visits.

Setting Data in Local Storage

To set data in local storage, you use the localStorage.setItemmethod.

This method takes two arguments: a key and a value.

Both the key and the value are stored as strings.


localStorage.setItem("username" , "JaneDoe");
localStorage.setItem("age" , "30");

In the above example, the key-value pairs username: JohnDoeand age: 30are stored in local storage.

Getting Data from Local Storage

To retrieve data from local storage, you use the localStorage.getItemmethod.

This method takes a single argument, the key, and returns the value associated with that key.


let username = localStorage.getItem("username");
let age = localStorage.getItem("age");
console.log(username); // Outputs: JohnDoe
console.log(age); // Outputs: 30

Here, the values for usernameand ageare retrieved and logged to the console.

Removing Data from Local Storage

To remove data from local storage, you use the localStorage.removeItemmethod.

This method takes a single argument, the key, and removes the key-value pair associated with that key.


localStorage.removeItem("username");

In the above example, the usernamekey-value pair is removed from local storage.

Clearing All Data from Local Storage

If you need to clear all data stored in local storage, you can use the localStorage.clearmethod.

This method removes all key-value pairs stored in local storage.


localStorage.removeItem("username");

This command will remove all data stored in local storage.

Storing Complex Data in Local Storage

Since local storage only stores strings, you need to serialize complex data types like objects or arrays into strings using JSON.stringifybefore storing them.

To retrieve and use this data, you need to parse it back into its original form using JSON.parse.


let user = {
  name: "John Doe",
  age: 30,
  email: "john.doe@example.com"
};

// Store object as string
localStorage.removeItem("username", JSON.stringify(use) );

// Retrieve and parse object
let retrievedUser = JSON.parse(localStorage.getItem("user"));

console.log(retrievedUser.name); // Outputs: John Doe
console.log(retrievedUser.age); // Outputs: 30
console.log(retrievedUser.email); // Outputs: john.doe@example.com

In the above example, an object is serialized into a JSON string before being stored, and then parsed back into an object when retrieved.

Checking for Local Storage Support

Not all browsers support local storage, so it's good practice to check for support before using it.

You can do this by checking for the presence of localStoragein the window object.


if (typeof(Storage) !== "undefined" ){ 
  // Local storage is supported
  localStorage.setItem("test" , "testValue");
  console.log(localStorage.getItem("test")); // Outputs: testValue
}else {
  // Local storage is not supported
  console.log("Local storage is not supported by this browser.");
} 

This code checks if local storage is available and then uses it accordingly.

Use Cases for Local Storage

Local storage is useful for storing data that should persist between sessions without needing to be sent to the server.

Common use cases include:

  • Saving user preferences or settings
  • Caching application state
  • Storing data for offline use
  • Keeping user sessions

Local storage in JavaScript provides a simple and efficient way to store data on the client side.

It is more powerful than cookies for storing larger amounts of data and does not affect server performance.

Understanding how to set, get, update, and remove data in local storage is essential for developing modern web applications that require persistent client-side storage.

Let's learn about Session Storage in the next chapter.