What APIs Does the localStorage Object Have?
LocalStorage is part of the Web Storage API, which enables web pages to store data locally within the user's browser. Below are the commonly used API methods for the LocalStorage object:
setItem(key, value): This method stores data in LocalStorage. It accepts two parameters:key(the name of the stored data) andvalue(the actual data to store). For example:
javascriptlocalStorage.setItem('username', 'JohnDoe');
getItem(key): This method retrieves the value stored in LocalStorage using the specifiedkey. If the key does not exist, it returnsnull. For example:
javascriptlet userName = localStorage.getItem('username'); console.log(userName); // Output: JohnDoe
removeItem(key): This method removes the data associated with the specifiedkeyfrom LocalStorage. For example:
javascriptlocalStorage.removeItem('username');
clear(): This method clears all data from LocalStorage. For example:
javascriptlocalStorage.clear();
length: A read-only property that returns the number of data items stored in LocalStorage. For example:
javascriptlet numberOfItems = localStorage.length; console.log(numberOfItems);
key(index): This method retrieves the key from LocalStorage based on the index. Indices start from 0. If the index is out of range, it returnsnull. For example:
javascriptlet firstKeyName = localStorage.key(0); console.log(firstKeyName);
Data stored in LocalStorage is always in string format, even when storing numbers or objects. To store objects, it's common to use the JSON.stringify method to convert the object to a string, and then use JSON.parse to convert it back upon retrieval. For example:
javascriptlet user = { name: 'John', age: 30 }; localStorage.setItem('user', JSON.stringify(user)); let retrievedUser = JSON.parse(localStorage.getItem('user')); console.log(retrievedUser); // Output: { name: 'John', age: 30 }
These are the main APIs of the LocalStorage object. It's important to note that while LocalStorage provides a convenient mechanism for local storage, it is not suitable for storing sensitive information because the data is stored in plain text and has no expiration time, making it vulnerable to cross-site scripting (XSS) attacks.