Reputation: 109
I have an application that has inside the local storage a variable named token.
I want to write a code that clears the console and the shows an alert(); with the aforementioned variable.
This is what I have managed to do so far
clear(); if(localStorage){alert(localStorage.getItem("token"));}
But I keep getting the error that localStorage is not defined. More precisely:
Uncaught ReferenceError: localStorage is not defined at <anonymous>:1:12
Any ideas?
Upvotes: 1
Views: 168
Reputation: 33
In some cases, you cannot use "localStorage" as a boolean.
As Gilad Bar suggested, use if (typeof localStorage !== "undefined")
instead.
Also, make sure that "token" isn't null or undefined.
Upvotes: 0
Reputation: 1322
I don't have the full context of your code, but if localStorage isn't defined then you can't check if it's value is defined.
For example, and that's true for any variable, if you don't define the variable bla
, then the following code will throw the same error:
if (bla) console.log(bla);
You should use if (typeof localStorage !== "undefined")
instead.
Furthermore, your browser doesn't necessarily support localStorage, so you should check that before. And using try-catch is also a good idea when working with localStorage.
Upvotes: 1