JavaScript Tutorial
JS - Introduction JS - Basic JS - Placement JS - Output JS - Statements JS - Syntax JS - Variables JS - Comments JS - Data Types JS - Operators JS - Operator Precedence JS - Condition JS - Switch JS - Functions JS - Objects JS - Loops For JS - Loops While JS - Break JS - Strings JS - String Methods JS - Numbers JS - Number Methods JS - Arrays JS - Array Methods JS - Array Iteration JS - Events JS - Event Listener JS - Event Propagation JS - Date JS - Math JS - Random JS - Boolean JS - Type Conversion JS - RegExp JS - Exception JS - Scope JS - Debugging JS - Hoisting JS - Strict Mode JS - this Keyword JS - Mistakes JS - Best Practices JS - Performance JS - Form Validation JS - ES6 Features
JS Objects
Object Definitions Object Properties Object Methods Object Constructors Object Prototypes
JS Functions
Function Definitions Function Parameters Function Call Function Apply Function Closures
JS HTML DOM
DOM Introduction DOM Methods DOM Selectors DOM HTML DOM CSS DOM Attributes DOM Navigation
JS Browser BOM
JS - Window JS - Screen JS - Location JS - History JS - Navigator JS - Popup Alert JS - Timing JS - Cookies
JS AJAX
AJAX - Introduction AJAX - XMLHttp AJAX - Request AJAX - Response AJAX - PHP
JS JSON
JSON - Introduction JSON - Syntax JSON - Data Types JSON - Parse JSON - Stringify JSON - Objects JSON - Arrays JSON - PHP JSON - JSONP
JS References
JavaScript Reference JavaScript Methods HTML DOM Reference

JavaScript Cookies

Cookies let you store information in user's web browser.


What is a Cookie?

A cookie is a small text file that lets you store a small amount of data (nearly 4KB) on the user's computer.

When a web server has sent a web page to a browser, the connection is shut down, and the server forgets everything about the user.

Cookies were invented to solve the problem "how to remember information about the user".

Cookies can be used for keeping track of information such as user preferences that the site can retrieve to personalize the page when user visits the website next time.

Cookies are saved in "name=value" pairs like:

username = Vishal

When a browser requests a web page from a server, cookies belonging to the page is added to the request. This way the server gets the necessary data to "remember" information about users.

Note: Don't store sensitive data such as a password or credit card information in cookies since it could potentially be manipulated by the malicious user.


Create a Cookie with JavaScript

In JavaScript, you can create, read, and delete cookies with the document.cookie property.

A cookie can be created like this:

You can also add an expiry date (in UTC time). By default, the cookie is deleted when the browser is closed:

With a path parameter, you can tell the browser what path the cookie belongs to. By default, the cookie belongs to the current page:


Read a Cookie with JavaScript

In JavaScript, cookies can be read like this:

Reading a cookie is a slightly more complex because the document.cookie property simply returns a string containing a semicolon and a space separated list of all cookies (i.e. name=value pairs, for example, cookie1=value; cookie2=value; cookie3=value). In order to get the individual cookie from this list, you need to make use of split() method to break it into individual name=value pairs, and search for the specific name.

This string doesn't contain the attributes such as expires, path, domain, etc. that may have been set for the cookie.



Change a Cookie with JavaScript

The only way to change or modify a cookie is to create another cookie with the same name and path as an existing one.

Note: Creating a cookie with the same name but with a different path will not change the existing one instead will add an additional cookie.


Delete a Cookie with JavaScript

Deleting a cookie is very easy. To delete a cookie:

  • Just set it once again using the same name, specifying an empty value
  • OR set the expires parameter to a passed date

Remember that if you've specified a path, or other attributes for the cookie, you'll also need to include them when deleting it.


JavaScript Cookie Example

In the example to follow, we will create a cookie that stores the name of a user.

The first time a user visits to the web page, he/she will be asked to fill in his/her name. The name is then stored in a cookie.

The next time the user visits at the same page, he/she will get the value that stored in the cookie.

For the example, we will create 2 JavaScript functions:

  • A function to set a cookie value
  • A function to get a cookie value

Storing Cookies

First, we create a function that stores the name of the visitor in a cookie variable.

Run code

Function explained:

The parameters of the function above are the name of the cookie (cname) and the value of the cookie (cvalue).

The function sets a cookie by adding together the cookie name, the cookie value, and the expires string (for 1 month).


Reading Cookies

Then, we create a function that shows the value of a specified cookie.

Run code

Function explained:

This function takes the cookie name as parameter (cname).

Get all cookies (allcookies = document.cookie).

Split document.cookie on semicolons into an array called cookieArr (cookieArr = allcookies.split(';')).

Loop through the cookieArr array (i = 0; i < cookieArr.length; i++), and read out each value (cookiePair = cookieArr[i]).

If the cookie is found (cname == cookiePair[0]), write the key and value of the cookie (cookiePair[0], cookiePair[1]).


All Together Now

Run code

Cookies Attributes

Cookies are a plain text data record of 5 attributes:

Attribute Description
Name=Value Cookies are set and retrieved in the form of key-value pairs
Expires The date the cookie will expire. If this is blank, the cookie will expire when the visitor quits the browser
Domain The domain name of your site
Path The path to the directory or web page that set the cookie. This may be blank if you want to retrieve the cookie from any directory or page
Secure If this field contains the word "secure", then the cookie may only be retrieved with a secure server. If this field is blank, no such restriction exists