Cookies are small pieces of data that are sent by a website to a user's web browser and stored on the user's computer or device. They are typically used to store information such as user preferences, login credentials, and shopping cart items.
Cookies are sent to the web server with every subsequent request made by the user's web browser to the same website. This allows the website to recognize the user and personalize their experience, such as displaying personalized content or remembering their login status.
In JavaScript, you can work with cookies using the document.cookie
property. Here are some examples of how you can create, read, update, and delete cookies:
Creating a cookie:
To create a cookie, you can set the document.cookie
property to a string that includes the name, value, and optional attributes of the cookie. For example:
document.cookie = "username=John Doe; expires=Thu, 18 Dec 2025 12:00:00 UTC; path=/";
This creates a cookie named username
with the value John Doe
, an expiration date of December 18, 2025, and a path of /
(meaning the cookie is accessible on all pages within the website).
Reading a cookie:
To read the value of a cookie, you can access the document.cookie
property and parse the string to find the value of the desired cookie. For example:
const cookies = document.cookie.split("; ");
for (let i = 0; i < cookies.length; i++) {
const parts = cookies[i].split("=");
const name = parts[0];
const value = parts[1];
if (name === "username") {
console.log("The value of the username cookie is: " + value);
}
}
This splits the document.cookie
string into an array of individual cookies, and then loops through each cookie to find the one with the name username
. Once the cookie is found, its value is logged to the console.
Updating a cookie:
To update the value or attributes of a cookie, you can create a new cookie with the same name and updated values or attributes, and set its expiration date to the current time plus the desired duration. For example:
const d = new Date();
d.setTime(d.getTime() + (7 * 24 * 60 * 60 * 1000)); // 7 days from now
const expires = "expires=" + d.toUTCString();
document.cookie = "username=Jane Doe; " + expires + "; path=/";
This creates a new cookie named username
with the value Jane Doe
, an expiration date of 7 days from the current time, and a path of /
.
Deleting a cookie:
To delete a cookie, you can create a new cookie with the same name and an expiration date in the past. For example:
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
This creates a new cookie named username
with no value, an expiration date of January 1, 1970 (which effectively deletes the cookie), and a path of /
.
Project:
index.html
<!DOCTYPE html>
<html>
<head>
<title>Cookie Example</title>
</head>
<body>
<h1>Cookie Example</h1>
<p id="username"></p>
<button onclick="setCookie()">Set Cookie</button>
<button onclick="getCookie()">Get Cookie</button>
<button onclick="deleteCookie()">Delete Cookie</button>
<script src="app.js"></script>
</body>
</html>
app.js
function setCookie() {
const d = new Date();
d.setTime(d.getTime() + (7 * 24 * 60 * 60 * 1000)); // 7 days from now
const expires = "expires=" + d.toUTCString();
document.cookie = "username=John Doe; " + expires + "; path=/";
alert("Cookie set!");
}
function getCookie() {
const cookies = document.cookie.split("; ");
for (let i = 0; i < cookies.length; i++) {
const parts = cookies[i].split("=");
const name = parts[0];
const value = parts[1];
if (name === "username") {
document.getElementById("username").innerHTML = "The value of the username cookie is: " + value;
}
}
}
function deleteCookie() {
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
alert("Cookie deleted!");
}
The localStorage
and sessionStorage
APIs are built-in browser features that allow web developers to store data on the client-side (i.e., in the user's browser). Both APIs provide a way to store key-value pairs of data, but there are some key differences between them.
- localStorage
The localStorage
API allows you to store data with no expiration date. This means that the data will persist even after the browser window or tab is closed, and will remain available until it is explicitly deleted or cleared. Some examples of data that could be stored in localStorage
include user preferences, saved game progress, or cached data.
Here's an example of how to use the localStorage
API in JavaScript:
// Store a value in localStorage
localStorage.setItem('key', 'value');
// Retrieve a value from localStorage
const value = localStorage.getItem('key');
// Remove a value from localStorage
localStorage.removeItem('key');
// Clear all values from localStorage
localStorage.clear();
Note that the setItem()
method is used to store a key-value pair in localStorage
, while the getItem()
method is used to retrieve the value associated with a given key. The removeItem()
method is used to remove a key-value pair, and the clear()
method is used to remove all key-value pairs from localStorage
.
- sessionStorage
The sessionStorage
API is similar to localStorage
, but with one key difference: the data stored in sessionStorage
is only available for the duration of the browser session. This means that the data will be cleared when the user closes the browser window or tab.
Here's an example of how to use the sessionStorage
API in JavaScript:
// Store a value in sessionStorage
sessionStorage.setItem('key', 'value');
// Retrieve a value from sessionStorage
const value = sessionStorage.getItem('key');
// Remove a value from sessionStorage
sessionStorage.removeItem('key');
// Clear all values from sessionStorage
sessionStorage.clear();
Note that the methods for working with sessionStorage
are identical to those for localStorage
.
In general, localStorage
is a good choice for storing data that needs to persist across browser sessions, while sessionStorage
is better suited for storing data that is only needed for the current browser session. Both APIs can be useful for storing data that needs to be accessible across multiple pages within a website.
Project:
index.html
<!DOCTYPE html>
<html>
<head>
<title>Web Storage Example</title>
</head>
<body>
<h1>Web Storage Example</h1>
<label for="input">Enter a value:</label>
<input type="text" id="input" name="input"><br><br>
<button onclick="storeLocal()">Store in localStorage</button>
<button onclick="retrieveLocal()">Retrieve from localStorage</button>
<button onclick="clearLocal()">Clear localStorage</button><br><br>
<button onclick="storeSession()">Store in sessionStorage</button>
<button onclick="retrieveSession()">Retrieve from sessionStorage</button>
<button onclick="clearSession()">Clear sessionStorage</button><br><br>
<div id="output"></div>
<script src="app.js"></script>
</body>
</html>
app.js
// Store a value in localStorage
function storeLocal() {
const input = document.getElementById('input').value;
localStorage.setItem('key', input);
document.getElementById('output').textContent = 'Value stored in localStorage';
}
// Retrieve a value from localStorage
function retrieveLocal() {
const value = localStorage.getItem('key');
document.getElementById('output').textContent = 'Value retrieved from localStorage: ' + value;
}
// Clear localStorage
function clearLocal() {
localStorage.clear();
document.getElementById('output').textContent = 'localStorage cleared';
}
// Store a value in sessionStorage
function storeSession() {
const input = document.getElementById('input').value;
sessionStorage.setItem('key', input);
document.getElementById('output').textContent = 'Value stored in sessionStorage';
}
// Retrieve a value from sessionStorage
function retrieveSession() {
const value = sessionStorage.getItem('key');
document.getElementById('output').textContent = 'Value retrieved from sessionStorage: ' + value;
}
// Clear sessionStorage
function clearSession() {
sessionStorage.clear();
document.getElementById('output').textContent = 'sessionStorage cleared';
}
This JavaScript code defines several functions that interact with the localStorage
and sessionStorage
APIs. The storeLocal()
function retrieves the value entered in the input field, stores it in localStorage
, and updates a message displayed in the output div. The retrieveLocal()
function retrieves the value associated with the 'key' in localStorage
and displays it in the output div. The clearLocal()
function clears all key-value pairs in localStorage
and displays a message in the output div. The storeSession()
, retrieveSession()
, and clearSession()
functions are identical to their localStorage
counterparts, but use the sessionStorage
API instead.
When the user interacts with the buttons on the web page, the corresponding JavaScript function is called, which stores or retrieves data from the appropriate storage API and updates the message displayed in the output div.
Both localStorage
and sessionStorage
allow you to store arrays and objects in addition to simple strings. To store an array or object, you simply need to convert it to a string using JSON.stringify()
before storing it, and then convert it back to its original form using JSON.parse()
when retrieving it.
Here's an example of how to store an array in localStorage
:
const myArray = [1, 2, 3];
localStorage.setItem('myArray', JSON.stringify(myArray));
In this example, the myArray
variable is first converted to a JSON string using JSON.stringify()
, and then stored in localStorage
using the setItem()
method.
To retrieve the array from localStorage
, you would use the getItem()
method and then parse the JSON string using JSON.parse()
:
const storedArray = JSON.parse(localStorage.getItem('myArray'));
In this example, the getItem()
method is used to retrieve the JSON string from localStorage
, and then JSON.parse()
is used to convert the string back to its original array form.
The same approach can be used to store and retrieve objects:
const myObject = { name: 'John', age: 30 };
localStorage.setItem('myObject', JSON.stringify(myObject));
const storedObject = JSON.parse(localStorage.getItem('myObject'));
In this example, the myObject
variable is first converted to a JSON string using JSON.stringify()
, and then stored in localStorage
using the setItem()
method. The getItem()
method is then used to retrieve the JSON string, which is converted back to its original object form using JSON.parse()
.
Note that the JSON.stringify()
and JSON.parse()
methods can also be used with sessionStorage
in the same way.
Project:
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Local Storage Example</title>
</head>
<body>
<h1>Local Storage Example</h1>
<form id="form">
<label for="name">Name:</label>
<input
type="text"
id="name"
/>
<label for="age">Age:</label>
<input
type="number"
id="age"
/>
<button type="submit">Add Person</button>
</form>
<ul id="people-list"></ul>
<script src="app.js"></script>
</body>
</html>
app.js
const form = document.querySelector('#form');
const nameInput = document.querySelector('#name');
const ageInput = document.querySelector('#age');
const peopleList = document.querySelector('#people-list');
// Load people from localStorage on page load
let people = JSON.parse(localStorage.getItem('people')) || [];
// Render people in the list
function renderPeople() {
peopleList.innerHTML = '';
for (let person of people) {
const li = document.createElement('li');
li.textContent = `${person.name} (${person.age})`;
peopleList.appendChild(li);
}
}
// Handle form submission
form.addEventListener('submit', event => {
event.preventDefault();
const person = {
name: nameInput.value,
age: ageInput.value
};
people.push(person);
localStorage.setItem('people', JSON.stringify(people));
renderPeople();
nameInput.value = '';
ageInput.value = '';
});
// Initial render
renderPeople();
This example shows how to store an array of objects in localStorage
. The web application allows the user to enter the name and age of a person, and when the user submits the form, the person is added to the people
array and the array is saved to localStorage
. On page load, the people
array is loaded from localStorage
and rendered in a list. Note how JSON.stringify()
is used to convert the people
array to a string before storing it in localStorage
, and JSON.parse()
is used to convert the string back to an array when loading it from localStorage
.
Unlike sessionStorage
, data stored in localStorage
has no expiration date by default. However, you can set an expiration date for your localStorage
data by storing an object that includes both the data and the expiration date.
Here's an example of how you can store expiring data in localStorage
:
// Store data with an expiration date of 1 hour from now
const expirationDate = new Date().getTime() + (60 * 60 * 1000); // 1 hour from now
const data = { foo: 'bar', expiration: expirationDate };
localStorage.setItem('myData', JSON.stringify(data));
In this example, an object is created that includes the data you want to store ({ foo: 'bar' }
) and an expiration date set to 1 hour from now. The object is then stringified using JSON.stringify()
and stored in localStorage
using the setItem()
method.
To retrieve the data and check if it has expired, you would first retrieve the object from localStorage
and then check the expiration date:
const storedData = JSON.parse(localStorage.getItem('myData'));
if (storedData && storedData.expiration && storedData.expiration > new Date().getTime()) {
// Data has not expired, use it as needed
const myValue = storedData.foo;
} else {
// Data has expired or does not exist, do something else
}
In this example, the getItem()
method is used to retrieve the JSON string from localStorage
, which is then parsed into an object using JSON.parse()
. The code then checks if the stored data exists (storedData
is not null
), and if it has not expired (storedData.expiration
is greater than the current time).
If the stored data is still valid, you can use it as needed. If the data has expired or does not exist, you can take appropriate action, such as fetching new data from the server.
Note that this approach requires you to manually check for expiration and handle expired data yourself. If you need more sophisticated expiration and caching behavior, you might consider using a library such as lscache
or store.js
.
In web development, a query string is a part of a URL that contains data that is passed to a server-side script, which can then use that data to generate a dynamic web page. Query strings are typically used to send parameters to a web page, allowing the page to display customized content based on the values of those parameters.
In JavaScript, you can manipulate the query string of a URL using the window.location.search
property. This property returns the query string portion of the current page's URL, including the question mark. For example, if the current URL is http://example.com/index.html?name=John&age=30
, then window.location.search
would return ?name=John&age=30
.
To manipulate the query string, you can use the URLSearchParams
API. This API provides methods for adding, modifying, and removing parameters from a query string. Here's an example:
// Get the current query string
let searchParams = new URLSearchParams(window.location.search);
// Get the value of a parameter
let name = searchParams.get('name'); // "John"
// Set the value of a parameter
searchParams.set('age', 31);
// Remove a parameter
searchParams.delete('name');
// Add a new parameter
searchParams.append('gender', 'male');
// Update the query string of the current URL
let newQueryString = searchParams.toString();
window.history.replaceState(null, null, '?' + newQueryString);
In this example, we create a new URLSearchParams
object based on the current query string, then use its methods to modify the parameters. Finally, we update the query string of the current URL using the replaceState
method of the window.history
object.
When the user clicks on the Set Cookie
button, a cookie with the name username
and the value John Doe
will be created and stored on their browser for 7 days. When the user clicks on the Get Cookie
button, the value of the username
cookie will be read and displayed in the paragraph with an ID of username
. When the user clicks on the Delete Cookie
button, the username
cookie will be deleted.
The setCookie()
function sets a new cookie named username
with the value John Doe
and an expiration date of 7 days from the current time. The getCookie()
function reads the value of the username
cookie and displays it in the paragraph with an ID of username
. The deleteCookie()
function deletes the username
cookie.
In this example, the index.html
file contains a simple HTML structure with a title, a heading, a paragraph with an ID of username
, and three buttons that call the setCookie()
, getCookie()
, and deleteCookie()
functions in the app.js
file.