3
var test = null;
if(test !== null){
    console.log('should not be logged in the console');//it worked
}


localStorage.setItem('foo',null);
console.log(localStorage.getItem('foo'));//logs null
if(localStorage.getItem('foo') !== null){
    console.log('should not be logged');//din't work, it's getting logged in the console
}

It seems the localStorage is storing the value null as string 'null'. So, the following code worked fine for me.

if(localStorage.getItem('foo') !== 'null'){

I have also ensured the code worked for me with setting the localStorage value something other than null.

This is actually not an answer. Because we may set localStorage value as string 'null' too. Not?

I know I can check like if(!variable){ but this will check for empty strings (""), null, undefined, false and the numbers 0 and NaN.

And there's a way to check for null only using like this:

if(variable === null && typeof variable === "object")

This might be a bug to Storage system? Is there any solution for checking actually null instead of 'null'?

Tushar
  • 85,780
  • 21
  • 159
  • 179
Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231
  • `localStorage.getItem('foo')` returns null as string . So use `if(localStorage.getItem('foo') !== 'null'){` – J Santosh Aug 31 '15 at 07:25
  • 2
    Everything stored in `localStorage` is in string format. – Satpal Aug 31 '15 at 07:25
  • 1
    *"This might be a bug to Storage system?"* -- No. Web-storage (session/local) are basically key-value pairs. [From this ref](https://w3c.github.io/webstorage/#the-storage-interface) - *Keys are strings. Any string (including the empty string) is a valid key. Values are similarly strings.*. Store empty string if you want to, but do not attempt to store null. Null has a special meaning here - key(n) returns null only if n is greater than or equal to the number of key/value pairs in the object. – Abhitalks Aug 31 '15 at 07:32

2 Answers2

9

According to this answer:
Storing Objects in HTML5 localStorage

localStorage is made to save String key-value-pairs, only!

null is an empty Object.

So this is not a bug, it is actually the expected behaviour.

Community
  • 1
  • 1
B. Kemmer
  • 1,517
  • 1
  • 14
  • 32
7

You can only store string in the localStorage.

So, when you save null value in localStorage, you're actually storing "null"(string) in the localStorage.

To check if value in localStorage is null, use ==.

Example:

localStorage.setItem('foo', null);
console.log(localStorage.getItem('foo')); //logs null as string
console.log(typeof localStorage.getItem('foo')); //logs string

if (localStorage.getItem('foo') != null) {
//                              ^^         // Don't use strict comparison operator here
    console.log('Should work now!');
}
Tushar
  • 85,780
  • 21
  • 159
  • 179