0

I have this javascript function:

  getToken: function () {
        return localStorage.jwtToken;
    },

  this.getToken()!=null //true, 

so basically this function returns "null" instead of null, how can I make the function return the null value?

  • 1
    Possible duplicate of [Storing Objects in HTML5 localStorage](https://stackoverflow.com/questions/2010892/storing-objects-in-html5-localstorage) – lucascaro Nov 13 '18 at 21:27
  • 1
    How did you *set* the value? You've confirmed that `this.getToken()` returns `"null"`? – Tyler Roper Nov 13 '18 at 21:31

3 Answers3

2

You probably did:

 localStorage.jwtToken = null;

to set it to null, but as localStorage can only contain string properties, it got stringified to "null". Instead of setting it to null set it to undefined, or just delete the key:

 localStorage.jwtToken = undefined;
 localStorage.removeItem("jwtToken");
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
0

If instead of "null" you want to return null, return this expression

getToken: function () {
        let token = localStorage.jwtToken;
        return (token === "null") ? null : token;
    }
Sergey Pleshakov
  • 7,964
  • 2
  • 17
  • 40
-2

this.getToken()!=null returns true because you are only checking the value.

If you want to check the value and type you need to check with !==.

this.getToken() !== null

Pablo Darde
  • 5,844
  • 10
  • 37
  • 55