About Lesson
Basic Operations
Setting Data
Use localStorage.setItem(key, value) to store data.
JavaScript
localStorage.setItem("username", "JohnDoe");
console.log("Data saved!");
Getting Data
Use localStorage.getItem(key) to retrieve data.
JavaScript
const username = localStorage.getItem("username");
console.log(username); // Outputs: JohnDoe
Removing Data
Use localStorage.removeItem(key) to delete a specific item.
JavaScript
localStorage.removeItem("username");
console.log("Data removed!");
Clearing All Data
Use localStorage.clear() to remove all stored data.
JavaScript
localStorage.clear();
console.log("All data cleared!");
Checking Length
Use localStorage.length to get the number of items stored.
JavaScript
console.log(localStorage.length); // Outputs the number of stored keys
Accessing Keys
Use localStorage.key(index) to retrieve the key at a specific index.
JavaScript
const key = localStorage.key(0);
console.log(key); // Outputs the first key