Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sessionStorage - set Item to null

Tags:

javascript

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"?

like image 692
Black Avatar asked Jun 29 '16 13:06

Black


People also ask

How do I set local storage to null?

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.

How can I tell if sessionStorage is empty?

write(sessionStorage. getItem('value1')); most browser will render it as null if its empty.

Does sessionStorage persist after refresh?

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 ).


2 Answers

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".

like image 82
James Thorpe Avatar answered Sep 17 '22 19:09

James Thorpe


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
like image 20
Rahul Malu Avatar answered Sep 19 '22 19:09

Rahul Malu