JavaScript Cookie

JavaScript is the language behind almost every website you will use. JavaScript is the language of the online world and is used in online communication, as well. The concept and need for cookies arose when developers wanted to store user information in the browser to avoid overloaded communication over a stateless HTTP server. A cookie is like a file containing some data that is stored on the user’s machine. The information stays on the computer, even if the user closes the website or closes the browser. This article provides an overview of the use of cookies in JavaScript.

Syntax

The syntax for creating and saving cookie is as follows:

document.cookie = "cookieName=cookieValue"

The cookie saves the data in key-value pairs.

Creating a Cookie

You can create a cookie by assigning a string to the document.cookie, for example, userName.

document.cookie="userName=John"

Getting a Cookie

Now, if we want to have a look at the Cookie, we can get the cookie by assigning document.cookie to a variable and then console it.

var cookieStat = document.cookie;
console.log(cookie.Stat);

Setting/Updating a Cookie

We can update a cookie as well using the same syntax we used for creating a cookie. To add the expiry date in the cookie, for example, we will use the following technique:

var expiryDate = new Date();

expiryDate.setDate(expiryDate.getDate() + 1)
expiryDate.toUTCString()

document.cookie = "userName=John"
document.cookie = "expires=" + expiryDate.toUTCString()

After updating, take a look at the cookie:

console.log(document.cookie)

You can see that cookie is updated.

Deleting a Cookie

There is no built-in method or object for deleting a cookie in Python, but a cookie is deleted when it expires. By assigning a past date to a cookie, you can delete it.

var expiryDate = new Date();

expiryDate.setDate(expiryDate.getDate() - 1)
expiryDate.toUTCString()

document.cookie = "userName=John"
document.cookie = "expires=" + expiryDate.toUTCString()

After assigning a past date, the cookie will no longer work and will self-delete by expiring.

Conclusion

So, this is how you can create a cookie, set or update a cookie, and delete a cookie in JavaScript. In this article, you learned about cookie usage in JavaScript, including how cookies can help you in development and save necessary user data. You can continue to learn more about JavaScript at linuxhint.com. Thank you!



from Linux Hint https://ift.tt/352pRQM

Post a Comment

0 Comments