Local Storage
The localStorage is a read-only property of the window objects. It stores data in a web browser specifically to the domain and protocol. It doesn’t get sent to the server as it is stored locally in the web browser with no expiration date. The data will not be deleted when the browser is closed and reopened.
Syntax:- window.localStorage
Methods
- setItem (key, value) – It allows to add a key/value pair to the storage object. If the key already exists, the name value will overwrite the old value.
- getItem(key) – It returns the value of the item that is set with the given key.
- key(n) – It returns the key of the item in the storage object at the nth index which can be useful for looping.
- removeItem(key) – It removes the item in the storage object with the given key.
Session Storage
The sessionStorage is a read-only property of the window object. It stores data in a web browser specifically to the domain and protocol for a particular session. It doesn’t get sent to the server. Data stored in sessionStorage gets cleared when the page session ends. A page session lasts for as long as the browser is open and survives over page reloads and restores.
Syntax:- window.sessionStorage
Methods
- setItem (key, value) – It allows to add a key/value pair to the storage object. If the key already exists, the name value will overwrite the old value.
- getItem(key) – It returns the value of the item that is set with the given key.
- key(n) – It returns the key of the item in the storage object at the nth index which can be useful for looping.
- removeItem(key) – It removes the item in the storage object with the given key.