Junior — Middle
Can you explain the differences between cookie and localStorage in web development?
sobes.tech AI
Answer from AI
Cookie and localStorage are two methods of storing data on the client side, but they have key differences:
- Storage capacity: cookies are usually limited to about 4 KB, while localStorage can store around 5-10 MB.
- Accessibility: cookies are automatically sent to the server with each HTTP request to the domain, while localStorage is only accessible on the client side via JavaScript.
- Lifetime: cookies can have a set expiration date, localStorage data persists until explicitly cleared.
- Security: cookies can be marked as HttpOnly, preventing access via JavaScript (more secure), while localStorage is always accessible via JS.
Example of using localStorage:
// Saving data
localStorage.setItem('username', 'Ivan');
// Retrieving data
const user = localStorage.getItem('username');
console.log(user); // Ivan
Example of setting a cookie:
document.cookie = "username=Ivan; expires=Fri, 31 Dec 9999 23:59:59 GMT; path=/";