Cookies are small pieces of data stored in the user's browser by websites. They are commonly used to remember information about users, such as login details, preferences, and session information. JavaScript allows developers to create, read, and delete cookies to store small amounts of data on the client side.
Cookies play an important role in web applications because they help maintain user sessions and personalize the user experience.
What are Cookies?
A cookie is a small text file that a website stores in the user's browser. Each cookie contains a key–value pair and can also include additional information such as expiration time and domain.
Creating a Cookie
JavaScript can create a cookie by assigning a value to the document.cookie property.
A cookie named "username" with value "Rahul" is stored in the browser.
Setting Cookie Expiration
By default, cookies are deleted when the browser is closed. However, developers can specify an expiration date so that the cookie remains stored for a longer period.
The cookie will remain stored until the specified expiration date.
Reading Cookies
JavaScript can access cookies using the document.cookie property. This property returns all cookies stored for the current website.
username=Rahul
Deleting a Cookie
A cookie can be deleted by setting its expiration date to a past date.
The cookie is removed from the browser.
Common Uses of Cookies
- Maintaining user login sessions
- Storing user preferences
- Tracking user behavior for analytics
- Saving website settings such as language or theme
Cookies vs Local Storage
Both cookies and local storage allow websites to store data in the browser, but they have some important differences.
- Cookies are automatically sent to the server with each request.
- Local storage data stays only in the browser.
- Cookies store smaller amounts of data compared to local storage.
Conclusion
Cookies are a useful way to store small amounts of data in the user's browser. They help websites remember user preferences, maintain login sessions, and personalize the user experience.
Although cookies are widely used, modern applications often combine them with Local Storage or Session Storage for better data management.
In the next tutorial, you will learn about Error Handling in JavaScript, which explains how JavaScript handles errors using try, catch, and finally blocks.

