How to Set Item in localStorage in JavaScript - Simple Guide
To set an item in
localStorage in JavaScript, use localStorage.setItem(key, value) where key is the name and value is the string you want to store. This saves data in the browser that persists even after the page is closed.Syntax
The localStorage.setItem() method takes two arguments:
- key: A string representing the name of the item.
- value: A string representing the value to store.
Both key and value must be strings. If you want to store other data types, convert them to strings first.
javascript
localStorage.setItem('key', 'value');
Example
This example shows how to save a user's name in localStorage and then retrieve it to display a greeting.
javascript
localStorage.setItem('username', 'Alice'); const name = localStorage.getItem('username'); console.log('Hello, ' + name + '!');
Output
Hello, Alice!
Common Pitfalls
Common mistakes when using localStorage.setItem() include:
- Trying to store non-string values without converting them first (e.g., objects or numbers).
- Using keys that are not strings.
- Not checking if
localStorageis available in the browser (some browsers or modes disable it).
Always convert data to strings using JSON.stringify() if storing objects.
javascript
/* Wrong way: storing an object directly */ const user = { name: 'Alice', age: 25 }; localStorage.setItem('user', user); // stores "[object Object]" which is not useful /* Right way: convert object to string */ localStorage.setItem('user', JSON.stringify(user)); /* To retrieve and parse back */ const storedUser = JSON.parse(localStorage.getItem('user')); console.log(storedUser.name); // Alice
Output
Alice
Quick Reference
localStorage.setItem(key, value) stores a string value under the given key.
Remember:
- Keys and values must be strings.
- Use
JSON.stringify()to store objects. - Use
localStorage.getItem(key)to read values.
Key Takeaways
Use localStorage.setItem(key, value) to save string data in the browser.
Always convert non-string data to strings with JSON.stringify before storing.
Retrieve stored data with localStorage.getItem(key).
localStorage data persists even after closing the browser tab.
Check if localStorage is supported before using it to avoid errors.