Cookies in JavaScript

Cookies in web programming are small scripts that get stored on user’s computer system from a website. They are left behind by a website visited by a user visits. Cookies play a vital role in giving a better user experience.  Cookies in JavaScript are useful for tracking details and storing session preferences. These details are useful for the purpose of user experience and website analytics.

JavaScript is a preferred scripting language to carry out cookie management in a web browser. Since JavaScript is browser side scripting language, it is widely used to manage the data with context to its visitors. Different web browsers may have different rules and functionalities for deploying cookies for a website.

Cookies are stored in the String data format.  Let’s discuss the mechanisms of managing Cookies in JavaScript

Set Cookies in JavaScript with document object

Cookies in JavaScript can be set in the browser directly by using HTTP response headers in JavaScript as well. Checkout this syntax where the cookie inputs parameters are accepted as key-value pairs. 



Here is the simple code describing the functions for carrying out cookie management and  manually setting a cookie:

document.cookie = “name=Sd; expires=Monday” ;

In the above example we have deployed one cookie by defining its name and the day of its expiration. Whenever next Monday arrives after its setting, cookie with name “Sd” will expire automatically.

Example – Cookies in JavaScript

Here is the example to understand management of cookies using JavaScript. In the example code alert() function is used to show the cookies present on a specific webpage. 

function cookie_alert() {

document.cookie.split() is used to split a cookie where ever semicolons are encountered in the string. 

var split_cookie= document.cookie.split(';');

A cookie can be reset by overriding the previous values through document.cookie function.

document.cookie = "name1=Sd; expires1=Monday" ;
document.cookie = "name2=joe; expires2=Tuesday" ;
document.cookie.split(";").find(row =>row.startsWith('name1'));

In the following example, a complete function is created that can be used as a get method to retrieve the contents of a saved cookie:

function getcookie()  
            var a=document.cookie.split("=");  
        alert("Name="+a[0]+" "+"expiry="+a[1]);  
        alert("COOKIE IS NOT AVAILABLE");  

Note: Instead of creating cookies, JQuery Plugins can also be used to read, write, and delete cookies on a web browser. You can refer this to read more about Cookies in JavaScript

Be First to Comment

Leave a Reply

Your email address will not be published.