Welcome to our deep dive into the world of JavaScript Cookies! šÆ
In this lesson, we'll explore how to create, read, update, and delete cookies using JavaScript. By the end, you'll have a solid understanding of this essential web development technique. š”
Let's get started!
Cookies are small text files stored on a user's browser by a web server. They are used to remember information about a user, such as login status or preferences, for a certain period.
Cookies are useful in maintaining user sessions, storing preferences, and personalizing user experience across multiple pages or sessions. They help in preserving data between browser sessions and are crucial in creating responsive and interactive web applications.
To create a cookie, we use the document.cookie property in JavaScript. Here's a simple example:
// Create a cookie named 'username' with value 'John Doe' and expiration of 1 hour
document.cookie = "username=John Doe; expires=Thu, 18 Dec 2024 12:00:00 UTC; path=/";š Note: The expires attribute sets the cookie's expiration date, while the path attribute determines the path for which the cookie is valid.
To read a cookie, we parse the document.cookie property:
// Read the 'username' cookie
function getCookie(name) {
let cookieValue = null;
const cookies = document.cookie.split(';');
for (let i = 0; i < cookies.length; i++) {
const cookie = cookies[i].trim();
if (cookie.startsWith(`${name}=`)) {
cookieValue = cookie.substring(name.length + 1);
break;
}
}
return cookieValue;
}
// Example usage:
const username = getCookie('username');
console.log(username); // Output: John Doeš Note: The getCookie function above is used to parse and return the value of a specific cookie.
To update a cookie, we simply overwrite the existing cookie with a new one. Here's an example:
// Update the 'username' cookie with a new value
document.cookie = "username=Jane Smith; expires=Thu, 18 Dec 2024 12:00:00 UTC; path=/";To delete a cookie, we can set its expiration date to the past:
// Delete the 'username' cookie
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:01 UTC; path=/";Which property is used to create a cookie in JavaScript?
That's it for our in-depth lesson on JavaScript Cookies! š Now, grab your browser and try implementing these techniques in your own projects. Happy coding! š»
Remember, practice makes perfect! Keep exploring, learning, and sharing your knowledge with others. š¤
Cheers! š»