The Journey of #100DaysOfCode (Baqer_Qabalan)

Day 7: Local Storage in JavaScript

:mag: What is Local Storage?

Local Storage is a web storage feature that allows you to store data in the browser. Unlike cookies, the storage limit is much larger (typically around 5MB) and the data is not sent to the server with every request.

:blue_book: Why Use Local Storage?

  • Persistence: Data remains stored even after the browser is closed and reopened.
  • Capacity: Can store more data compared to cookies.
  • Simple API: Easy to use with a straightforward API.

:sparkles: Basic Usage of Local Storage

Here’s how you can use Local Storage to store, retrieve, and remove data:

Storing Data

To store data, use the setItem method. The data is stored as a key-value pair.

// Store a string
localStorage.setItem('name', 'John Doe');

Retrieving Data

To retrieve data, use the getItem method. Remember to parse it back to an object if it was stored as a JSON string.

// Retrieve a string
const name = localStorage.getItem('name');
console.log(name); // Outputs: John Doe

Removing Data

To remove data, use the removeItem method.

localStorage.removeItem('name');

Clearing All Data

To clear all data stored in Local Storage, use the clear method.

localStorage.clear();

As a conclusion, Local Storage is a powerful feature for storing data on the client side.
100daysofcode lebanon-mug

3 Likes