Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

The Cookie String

The document.cookie property appears as a text string but behaves differently. New cookies are appended, not overwritten, so reading document.cookie will show a list of name-value pairs.

cookie1 = value; cookie2 = value

To obtain the value of a specific cookie, you must create a JavaScript function that searches for the cookie’s value within the cookie string.

JavaScript Cookie Example

In the following example, we will create a cookie that stores the name of a visitor.

When a visitor first arrives on the webpage, they will be prompted to enter their name, which will then be stored in a cookie.

The next time the visitor returns to the same page, a welcome message will be displayed.

For this example, we will create three JavaScript functions:

  1. A function to set a cookie value.
  2. A function to get a cookie value.
  3. A function to check if a cookie exists.