Cookies are small text files that stored on a user’s computer or device when they visit a website. They are created by a website’s server and contain information that helps the website remember certain user preferences, track user activities, and enhance the overall browsing experience.
Purposes
- Manage Session: manage user session on website
- Personalization: Cookies can remember user language setting or display preferences etc.
- Tracking and Analytics: Track user behavior on website
- Advertising: They can track users’ browsing habits and interests to display targeted advertisements based on their preferences.
Example:
// Set a cookie with a name "username" and value "John Doe" that expires in 7 days
document.cookie = "username=John Doe; expires=" + new Date(Date.now() + (1 * 24 * 60 * 60 * 1000)).toUTCString();
// Retrieve the value of the "username" cookie
var cookies = document.cookie.split('; ');
var usernameCookie;
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i].split('=');
if (cookie[0] === "username") {
usernameCookie = cookie[1];
break;
}
}
console.log(usernameCookie); // Outputs "John Doe"
Cookies Vs Local Storage Vs Session Storage

It’s important to note that cookies are typically designed to be harmless and do not contain malicious code or software. However, concerns about privacy and data security have arisen due to the potential for cookies to store and track sensitive information. To address these concerns, modern web browsers provide options for users to manage and control cookie settings, including accepting or blocking cookies from specific websites. Additionally, websites often include privacy policies that explain how they use cookies and provide users with options to opt out of certain tracking or advertising practices.