Cookies in JavaScript: Ultimate Guide

A cookie is a piece of data that is stored on your computer to be accessed by your browser. You also might have enjoyed the benefits of cookies knowingly or unknowingly. Have you ever saved your facebook password so that you do not have to type it each and every time you try to login? If yes, then you are using cookies. Cookies are saved as key/value pairs.
Relevance of Cookies
The communication between a web browser and server happens using a stateless protocol named HTTP. Stateless protocol treats each request independent. So, the server does not keep the data after sending it to the browser. But in many situations, the data will be required again. Here comes cookies into picture. With cookies, the web browser will not have to communicate with the server each time the data is required. Instead, it can be fetched directly from the computer.
Create, Access and Remove Cookies
You can create cookies using document.cookie property like this.
?
1
document.cookie = "cookiename=cookievalue"
You can even add expiry date to your cookie so that the particular cookie will be removed from the computer on the specified date. The expiry date should be set in the UTC/GMT format. If you do not set the expiry date, the cookie will be removed when the user closes the browser.
?
1
document.cookie = "cookiename=cookievalue; expires= Thu, 21 Aug 2014 20:00:00 UTC"
You can also set the domain and path to specify to which domain and to which directories in the specific domain the cookie belongs to. By default, a cookie belongs to the page that sets the cookie.
?
1
document.cookie = "cookiename=cookievalue; expires= Thu, 21 Aug 2014 20:00:00 UTC; path=/ "
//create a cookie with domain to the current page and path to the entire domain.
You can access the cookie like this which will return all the cookies saved for the current domain.
?
1
var x =  document.cookie
To delete a cookie, you just need to set the value of cookie to empty and set the value of expires to a passed date.
?
1
document.cookie = "cookiename= ; expires = Thu, 01 Jan 1970 00:00:00 GMT"
Try this yourself:
This code is editable. Click Run to Execute
1
2
    <html>
3
4
    <head>
5
6
    <title>Cookie!!!</title>
7
8
    <script type="text/javascript">
9
10
11
    function createCookie(cookieName,cookieValue,daysToExpire)
12
13
    {
14
15
    var date = new Date();
16
17
    date.setTime(date.getTime()+(daysToExpire*24*60*60*1000));
18
19
    document.cookie = cookieName + "=" + cookieValue + "; expires=" + date.toGMTString();
20
21
    }
22
23
    function accessCookie(cookieName)
24
25
    {
26
27
    var name = cookieName + "=";
28
29
    var allCookieArray = document.cookie.split(';');
30
31
    for(var i=0; i<allCookieArray.length; i++)
32
33
      {
34
35
    var temp = allCookieArray[i].trim();
36
37
      if (temp.indexOf(name)==0)
38
39
         return temp.substring(name.length,temp.length);
40
41
      }
42
43
    return "";
44
45
    }
46
47
    function checkCookie()
48
49
    {
50
51
    var user = accessCookie("testCookie");
52
53
    if (user!="")
54
55
      alert("Welcome Back " + user + "!!!");
56
57
    else
58
59
      {
60
61
      user = prompt("Please enter your name");
62
63
      num = prompt("How many days you want to store your name on your computer?");
64
65
      if (user!="" && user!=null)
66
67
        {
68
69
    createCookie("testCookie", user, num);
70
71
        }
72
73
      }
74
75
    }
76
77
    </script></head>
78
79
    <body onload="checkCookie()"></body>
80
81
    </html>
82