JavaScript .getItem(key)
Published Aug 2, 2023
Contribute to Docs
The .getItem() method takes a key as an argument and returns the associated value. If the key is not present in the Storage object, it returns null.
The Storage object can be either a localStorage object or a sessionStorage object.
Syntax
localStorage.getItem(keyName)
sessionStorage.getItem(keyName)
The keyName parameter is required and it’s a string containing the name of the key to retrieve the value of.
Note: The
Storage.lengthproperty can be used to test whether the storage object is empty or not.
Example
Below is a basic example of implementing the .getItem() method to retrieve the value of a local storage item:
localStorage.setItem('userName', 'Luigi');console.log(localStorage.getItem('userName'));
The code above results in the following output:
Luigi
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