Code Snippets library
Code snippets library is a collection of short, ready-to-use code snippets with practical examples that you can quickly copy and use in your projects. It helps save time and solve common problems without digging through documentation.
3 ways to save data in the browser
// 1. LOCALSTORAGE
// Save a string
localStorage.setItem("name", "John");
// Save an array
const fruits = ["apple", "banana", "pear"];
localStorage.setItem("fruits", JSON.stringify(fruits));
// Save an object
const user = { name: "Alice", age: 25 };
localStorage.setItem("user", JSON.stringify(user));
// 2. SESSIONSTORAGE
// Save an object
sessionStorage.setItem("settings", JSON.stringify({ theme: "dark", fontSize: 14 }));
// 3. COOKIES
// Save a string (valid for 7 days)
document.cookie = "token=abc123; max-age=" + 7*24*60*60;
// Save an array
const colors = ["red", "green", "blue"];
document.cookie = `colors=${JSON.stringify(colors)}; max-age=${7*24*60*60}`;
// Save an object
const product = { id: 101, name: "Laptop", price: 2500 };
document.cookie = `product=${JSON.stringify(product)}; max-age=${7*24*60*60}`;