JavaScript cookies are small data stored on a user's device by a web browser. These cookies play a crucial role in web development, enabling websites to store and retrieve information about user preferences, session states, and other data. Cookies facilitate a more personalized browsing experience by allowing websites to remember user actions and preferences. They are widely used for user authentication, tracking, and maintaining session states.
Creating Cookie in JavaScript
Cookies are created by a web server and sent to the user's browser as part of the HTTP response headers.
Creating cookies in JavaScript involves using the document.cookie
object to set key-value pairs and additional parameters. To create a cookie, assign a string containing the desired cookie information to document.cookie
. This string can include attributes like expiration date, domain, and path.
Example: To demonstrate creating a cookie in JavaScript using a document.cookie method.
JavaScript
document.cookie =
"courseName=webDeveopment bootcamp; expires =
Thu, 5 March 2030 12:00:00 UTC; path = /";
Output:
courseName= "webDeveopment bootcamp; expires = Thu, 5 March 2030 12:00:00 UTC; path = /"
Reading Cookie in JavaScript
JavaScript allows developers to read cookies using the document.cookie
property, which stores all cookies as a string. To extract specific values, developers often create functions that parse this string. Security considerations, like proper decoding and HttpOnly attributes, are crucial.
Example: To demonstrate reading an already created cookie in JavaScript.
JavaScript
function getCookie(cookieName) {
const cookies = document.cookie.split('; ');
for (const cookie of cookies) {
const [name, value] = cookie.split('=');
if (name === cookieName) {
return decodeURIComponent(value);
}
}
return null;
}
const courseName = getCookie('courseName');
console.log('Course Name:', courseName);
Output:
Course Name: webDeveopment bootcamp
Changing Cookie in JavaScript
JavaScript enables the modification of cookies by updating their values or attributes. Developers use the document.cookie
property to both read and write cookies. When changing a cookie, it's crucial to consider parameters like expiration date, path, and security attributes.
Example: To demonstrate changing an already existing cookie in JavaScript.
JavaScript
document.cookie =
"courseName=WebDevelopmentBootcamp;
expires=Thu, 5 March 2030 12:00:00 UTC; path=/";
function changeCookieValue(cookieName, newValue) {
document.cookie =
`${cookieName}=${newValue};
expires=Thu, 5 March 2030 12:00:00 UTC; path=/`;
}
changeCookieValue('courseName', 'AdvancedJavaScriptCourse');
Output:
Course Name: WebDevelopmentBootcamp
Course Name after Change: AdvancedJavaScriptCourse
Deleting Cookie in JavaScript
JavaScript provides a way to delete cookies by setting their expiration date in the past. When a cookie's expiration date is in the past, the browser automatically removes it. Developers use the document.cookie
property to delete cookies, ensuring a clean and secure user experience.
Example: To demonstrate deleting a cookie in JavaScript using
JavaScript
document.cookie =
"courseName=WebDevelopmentBootcamp;
expires=Thu, 5 March 2030 12:00:00 UTC; path=/";
function deleteCookie(cookieName) {
document.cookie =
`${cookieName}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;`;
}
deleteCookie('courseName');
Output:
Course Name: WebDevelopmentBootcamp
Cookie 'courseName' deleted.
Similar Reads
JavaScript Events
JavaScript Events are actions or occurrences that happen in the browser. They can be triggered by various user interactions or by the browser itself. [GFGTABS] HTML <html> <script> function myFun() { document.getElementById( "gfg").innerHTML = "GeeksforGeeks"; } </
3 min read
What is JavaScript ?
JavaScript is a powerful and flexible programming language for the web that is widely used to make websites interactive and dynamic. JavaScript can also able to change or update HTML and CSS dynamically. JavaScript can also run on servers using tools like Node.js, allowing developers to build entire
6 min read
JavaScript String Exercise
JavaScript string is a primitive data type and is used for storing and manipulating a sequence of characters. It can contain zero or more characters within single or double quotes. This article contains a wide collection of JavaScript Programming examples based on String. [GFGTABS] JavaScript let s
7 min read
ES6 Cookies
Cookies are basically a storage facility of web browsers. It comes under the Web Storage of a browser which is a local or client storage facility. The data are in the browser even after the browser window is closed in many websites there is need of remembering session information, such as, when we l
7 min read
PHP Cookies
Cookies in PHP are used for maintaining state and storing user-specific information across multiple page visits. Since HTTP is a stateless protocol, every page request is independent, making it difficult to remember user preferences, authentication status, or other details between visits. Cookies al
10 min read
How to clear all cookies using JavaScript ?
Cookies allow clients and servers to exchange information via HTTP, enabling state management despite HTTP being a stateless protocol. When a server sends a response, it can pass data to the user's browser in the form of key-value pairs, which the browser stores as cookies. On subsequent requests to
2 min read
cookies in Next JS
Next.js provides cookies methods that allow you to store small pieces of data on the client side. It provides methods to store, delete, components and retrieve the cookie. cookies function can only used in server components. To store and delete the cookie at the client side using the cookies functio
3 min read
How to Get Cookie by Name in JavaScript?
Getting a specific name in JavaScript involves parsing the document's cookie string contains all cookies in a single string separated by semicolons and space. The goal is to extract the value of a specific cookie by the name given. The Cookie is defined as a small piece of data that is stored on the
4 min read
JavaScript History object
The JavaScript History object contains the browser's history. First of all, the window part can be removed from window.history just using the history object alone works fine. The JS history object contains an array of URLs visited by the user. By using the history object, you can load previous, forw
3 min read
Introduction to JavaScript
JavaScript is a versatile, dynamically typed programming language used for interactive web applications, supporting both client-side and server-side development, and integrating seamlessly with HTML, CSS, and a rich standard library. JavaScript is a single-threaded language that executes one task at
8 min read