setItem() Method – How to Store Items in Web Storage
The setItem() method stores its key and value arguments inside the specified web storage object.
Syntax of the setItem()
Method
setItem()
accepts two required arguments. Here is the syntax:
webStorageObject
represents the storage object you wish to manipulate—that is,localStorage
orsessionStorage
.key
is the first argument accepted bysetItem()
. It is a required string argument representing the name of the web storage property you want to create or update.value
is the second argument accepted bysetItem()
. It is a required string argument specifying the value of thekey
you are creating or updating.
Examples
Below are examples of the setItem()
method.
How to store data in session storage
- Invoke
sessionStorage
’ssetItem()
method. - Provide the name and value of the data you wish to store.
Note that your browser’s session storage may contain additional data if it already uses the storage object to store information.
How to store data in local storage
- Invoke
localStorage
’ssetItem()
method. - Provide the name and value of the data you wish to store.
Note that your browser’s local storage may contain additional data if it already uses the storage object to store information.
Important Stuff to Know about Storing Data in Web Storage
It is best to serialize objects before storing them in local or session storage. Otherwise, the computer will store the object as "[object Object]"
.
Example 1: Store an object in the web storage without serializing it
You can see that the computer stored the object as "[object Object]"
because we did not serialize it.
Example 2: Store a serialized object in the web storage
We used JSON.stringify()
to convert the object to JSON before storing it in the web storage.