JS Cookies šŸŖšŸ”‘

beginner
22 min

JS Cookies šŸŖšŸ”‘

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!

What are Cookies? šŸ“

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.

Why Use Cookies? šŸ’”

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.

Creating Cookies šŸŽÆ

To create a cookie, we use the document.cookie property in JavaScript. Here's a simple example:

javascript
// 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.

Reading Cookies šŸ”

To read a cookie, we parse the document.cookie property:

javascript
// 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.

Updating Cookies šŸ“

To update a cookie, we simply overwrite the existing cookie with a new one. Here's an example:

javascript
// Update the 'username' cookie with a new value document.cookie = "username=Jane Smith; expires=Thu, 18 Dec 2024 12:00:00 UTC; path=/";

Deleting Cookies šŸ—‘ļø

To delete a cookie, we can set its expiration date to the past:

javascript
// Delete the 'username' cookie document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:01 UTC; path=/";

Quiz šŸŽ²

Quick Quiz
Question 1 of 1

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! šŸ»

  • CodeYourCraft Team 🌟