Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is null stored as a string in localStorage?

In the Chrome console I set foo to null:

localStorage.setItem("foo",null)

Then I test, whether it is null:

console.log(localStorage.getItem("foo")==null)

prints false.

Then I test, whether it is the string "null":

console.log(localStorage.getItem("foo")=="null")

prints true.

I thought that null was a legitimate Javascript value. Storing it as the string "null" is very counter intuitive and caused a strange bug in an otherwise working program, when I cleared the localStorage in the browser manually.

like image 927
sbtpr Avatar asked Nov 07 '17 05:11

sbtpr


People also ask

Why is local Storage Null?

If the key does not exist, null is returned. localstorage are browser dependent, NodeJs is server side. This difference is that the in operator will walk the prototype chain, but getItem will only return data set on the object itself.

Can localStorage be 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.

Why localStorage getItem returns NULL?

The getItem() method of the Storage interface, when passed a key name, will return that key's value, or null if the key does not exist, in the given Storage object.

Can local Storage only store strings?

The localStorage is an instance of the Storage type that allows you to store persistent data in the web browsers. The localStorage can store only strings. To store objects, you convert them to strings using the JSON.


2 Answers

Please see https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

All values are stored as strings in local storage. You should stringify data before storing it and parse data after retrieving it:

localStorage.setItem("foo", JSON.stringify(null));
var value = JSON.parse(localStorage.getItem("foo"));
console.log(value === null);
like image 56
Alec Fenichel Avatar answered Oct 21 '22 19:10

Alec Fenichel


As per spec, localstorage uses Storage object interface

interface Storage {
  readonly attribute unsigned long length;
  DOMString? key(unsigned long index);
  getter DOMString? getItem(DOMString key);
  setter void setItem(DOMString key, DOMString value); //notice this line
  deleter void removeItem(DOMString key);
  void clear();
};

setter method translates to setItem, accepts only DOMString

As per documentation

DOMString is a UTF-16 String. As JavaScript already uses such strings, DOMString is mapped directly to a String.

Passing null to a method or parameter accepting a DOMString typically stringifies to "null".

like image 40
gurvinder372 Avatar answered Oct 21 '22 21:10

gurvinder372