I'm using a system to alert users when a major update has happened to a site, and I do it with LocalStorage, when I made the system, I made the system check if tip was "null", then set "tip" to true when they got the alert. Now, I would like to set the 'tip' localstorage back to null, and use "tip2" instead.
Would I do this? localStorage.setItem('tip', 'null');
Use the clear() method to delete all items in localStorage . This method, when invoked, clears the entire storage of all records for that domain. It does not receive any parameters.
Because LocalStorage context is per domain. You can't save an item on one domain, i.e http://foo.com, then go to another domain http://bar.com and access it there. If you setItem() within http://foo.com you can only getItem() within http://foo.com.
Storage removeItem() Method The removeItem() method removes the specified Storage Object item. The removeItem() method belongs to the Storage Object, which can be either a localStorage object or a sessionStorrage object.
localStorage.removeItem('tip')
if you are aiming to remove the key
localStorage.setItem('tip', 'null')
if you just want to set it to the string "null"
Any localStorage item either has a string value, or it does not exist. No other type is possible, therefore no variation of null is possible either.
The confusing part is that as you noticed in your example, if you call localStorage.getItem('tip') and it does not exist, you’ll see a null return value in the debugger or when attempting to display the value.
As unintuitive as this is, it doesn’t mean a local storage item actually exists with a value of null. It really means the item 'tip' does not exist at all. There is not even a single internal trace anywhere of anything related to the key ‘tip’.
For an item that does exist, if you are trying to set the item "back to null" (which is impossible), what you should be doing instead is to remove the item.
In your example, this will cause you see the return value displayed as null again, like when you first called localStorage.getItem('tip'), even though it’s not null, it just doesn’t exist at all. To do that you can remove the item as described below.
Just remember all you ever need is get, set, and remove.
localStorage.getItem('tip')
// Get item valuelocalStorage.setItem('tip','cool stuff')
// Set item valuelocalStorage.removeItem('tip')
// Remove itemif (localStorage.getItem('tip') === null)
// Check if item exists
Technically, @Michael Theriot‘s answer was suggesting to set the item tip to a string value of "null". That’s not much different that setting it to “dog”, in that neither one of them is actually a system recognized null value.
I’m guessing that’s not what you meant, however even if it were, I would tend to advise against the practice because it can become confusing to others maintaining your code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With