I check if a sessionStorage Variable is null, and if true initialize it with "BAR". Otherwhise there should appear a console message with the value of the variable.
sessionStorage.setItem("Foo", null); //I know this would make no sense at this part, this is just here for demo.
if (sessionStorage.getItem("Foo") == null) {
sessionStorage.setItem("Foo", "BAR");
} else {
console.log("Foo != null (proof = '", sessionStorage.getItem("Foo"), "')");
}
However, It always goes to the else statement and i get the console message which is telling me that the variable is "null", but if it is really "null" then why it is not initialized with "BAR"?
There is no way to set a localStorage item to have a value of null. Use remove instead. 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.
write(sessionStorage. getItem('value1')); most browser will render it as null if its empty.
Web storage objects localStorage and sessionStorage allow to save key/value pairs in the browser. What's interesting about them is that the data survives a page refresh (for sessionStorage ) and even a full browser restart (for localStorage ).
Per your edit, setItem
requires the value passed in to be a string (a DOMString
to be precise), anything else will be coerced to a string.
In your case, you pass in null
, which is coerced to "null"
. When you call getItem
, you get a string back, which isn't null
, so your code falls into the else
block.
If you actually want to clear out an item from storage, the correct method to use is removeItem
:
sessionStorage.removeItem("Foo");
Calling getItem
now would result in a return value of null
, not "null"
.
HTML5 storage: sessionStorage or localStorage accepts a string. If a string value is not passed it will convert it to string and save. Hence we should convert the value to string using (JSON.stringify(value)) and after fetching we should again convert it to the original value.
var val = null;
//save to storage
sessionStorage.setItem('a',JSON.stringify(val));
//fetch from storage
var stringValue = sessionStorage.getItem('a'); //outputs "null"
var originalValue = JSON.parse(sessionStorage.getItem('a')); //outputs null
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