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
JavaScript Cookies
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.
Table of Content
- Creating Cookie in JavaScript
- Reading Cookie in JavaScript
- Changing Cookie in JavaScript
- Deleting Cookie in JavaScript