JavaScript Interview Question #135
What are cookies, and how are they different from Web Storage?
Generators, Browser Storage, Security & Advanced Runtime Concepts Senior Advanced
Quick Interview Answer
Cookies are small pieces of data associated with a domain and path. Depending on their attributes, cookies can be automatically included with matching HTTP requests, which makes them fundamentally different from localStorage and sessionStorage.
Detailed Explanation
Cookies are small pieces of data associated with a domain and path. Depending on their attributes, cookies can be automatically included with matching HTTP requests, which makes them fundamentally different from localStorage and sessionStorage.
Security-sensitive cookies can use attributes such as HttpOnly, Secure, and SameSite. JavaScript cannot read HttpOnly cookies, which is useful for protecting certain authentication cookies from direct script access. Cookie behavior must be designed together with server-side security requirements.
Code Example
// JavaScript can access only cookies that are not HttpOnly.
document.cookie =
"theme=dark; Path=/; SameSite=Lax";
console.log(document.cookie);
// Authentication cookies are commonly created by the server
// with appropriate Secure, HttpOnly and SameSite settings.