JavaScript 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
Storageobject is particular to the protocol of the document. ThelocalStorageorsessionStorageobject forhttp://codecademy.comwill be a different object than thelocalStorageorsessionStorageobject returned forhttps://codecademy.com.
Note: The behavior of
Storageobjects for documents loaded from the local filesystem (i.e.file:) is undefined. Many browsers define a separateStorageobject 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 elements in an array, characters in a string, or items in array-like objects such as NodeLists.
- .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.
Learn JavaScript on Codecademy
- Front-end engineers work closely with designers to make websites beautiful, functional, and fast.
- Includes 34 Courses
- With Professional Certification
- Beginner Friendly.115 hours
- Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.
- Beginner Friendly.15 hours