JavaScript Create and Delete Cookies

As you know, cookies are small files containing system related information.

JavaScript Create and Delete Cookies Example

Here is an example demonstrates how to create and delete cookie in JavaScript:

   <title>JavaScript Create and Delete Cookies</title>
   <script type="text/javascript">
   function getCookie(cookie_name)
            if (document.cookie.length>0)
               cookie_start=document.cookie.indexOf(cookie_name + "=");
               if (cookie_start!=-1)
                  cookie_start=cookie_start + cookie_name.length+1;
                  if (cookie_start==-1) 
                     return unescape(document.cookie.substring(cookie_start,cookie_start));
            return "";
         function setCookie(cookie_name,cookie_value,expiredays)
            var exdate=new Date();
            document.cookie=cookie_name+ "=" +escape(cookie_value)+((expiredays==null) ? "" : ";expires="+exdate.toUTCString());

         function checkCookie()

            if (mycookie!=null && mycookie!="")
               alert('Welcome again '+mycookie+'! \n The cookies has already been created.');
               mycookie=prompt('Please enter your name:',"");
               if (mycookie!=null && mycookie!="")

         function eraseCookie() 
            alert('The cookie has been successfully erased.');

<h3>JavaScript Create and Delete Cookies Example</h3>
<p>Click on the <b>Create Cookie</b> button to create the cookie.</p>
<input type="button" onclick="checkCookie()" value="Create Cookie">
<p>Click on the <b>Delete Cookie</b> button to delete the cookie.</p>
<input type="button" onclick="eraseCookie()" value="Delete Cookie">


Here is the sample output of the above JavaScript create and delete cookie example code. This is the initial output:

javascript create cookies

To create cookie, click on the Create Cookie button. After clicking on Create Cookie button, enter the value (name) of the cookie as shown in the following figure:

create and read cookies javascript example

Now, click on OK button to successfully create your cookie. To delete cookie, just click on the Delete Cookie button. After clicking on the Delete Cookie button, you will get the output as shown in the following figure:

javascript delete cookies

JavaScript Online Test

« Previous Tutorial Next Tutorial »

Follow/Like Us on Facebook

Subscribe Us on YouTube