Storage
A Storage
object allows the addition, modification, and deletion of stored key/value pairs. The keys and values stored are always UTF-16 strings. Integer keys are converted to strings. The session storage for a domain is called from an object named sessionStorage
. Local storage is stored in an object called localStorage
.
The two Storage
objects are as follows:
localStorage
: Data is saved for the document’s origin, and persists across browser sessions. The data has no expiration date.sessionStorage
: Data is saved for the document’s origin, but persists only for the duration of the browser session.
Note: The
Storage
object is particular to the protocol of the document. ThelocalStorage
orsessionStorage
object forhttp://codecademy.com
will be a different object than thelocalStorage
orsessionStorage
object returned forhttps://codecademy.com
.
Note: The behavior of
Storage
objects for documents loaded from the local filesystem (i.e.file:
) is undefined. Many browsers define a separateStorage
object for eachfile:
URL, but it is not best practice to rely on this behavior.
Example
The following example shows adding a key/value pair to localStorage
, retrieving it, and removing it.
localStorage.setItem('dataKey', 'dataValue');const data = localStorage.getItem('dataKey');console.log(data);localStorage.removeItem('dataKey');
The example results in the following output:
dataValue
Below is a list of the Storage
object’s methods and properties:
Storage
- .clear()
- Removes all keys in a Storage object.
- .getItem(key)
- Returns the value of the key on the given data item.
- .length
- Returns the number of items in an array or the number of characters in a string.
- .removeItem()
- Removes a key-value pair from the local storage based on the specified key.
- .setItem()
- Updates the value to the specified storage object key, if it exists, else adds the key to the object.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.