220

Why this does not work ?

if(typeof(localStorage.getItem("username"))=='undefined'){ alert('no'); }; 

The goal is to redirect the user from the index page to the login page if not already logged. Here the localStorage.getItem("username")) variable is not defined for the moment.

It's for an ios phonegap app.

2
  • 2
    I'm surprised no one said it yet - client side security is highly discouraged. One can simply hit F12 and run localStorage['username']='admin' then mess with your website. Commented Apr 7, 2016 at 14:07
  • 5
    @oriadam I hope that no one is basing the authorization on the localStorage, but it is perfectly fine storing the JWT accessToken in the localStorage. Commented Oct 28, 2017 at 17:03

4 Answers 4

440

Quoting from the specification:

The getItem(key) method must return the current value associated with the given key. If the given key does not exist in the list associated with the object then this method must return null.

You should actually check against null.

if (localStorage.getItem("username") === null) { //... } 
Sign up to request clarification or add additional context in comments.

8 Comments

Thanks, it was my first mistake ! But it doesnt' work too with if(typeof(localStorage.getItem("username"))===null){ alert('no') };
Typeof of null is "null", not null (hope I'm making sense).
@Gabriel: Remove typeof(..). Check my answer again.
It's worth noting that the constraints FF (28.0) imposes on its localStorage table allows null values: CREATE TABLE webappsstore2 (scope TEXT, key TEXT, value TEXT, secure INTEGER, owner TEXT) while Chrome does not: CREATE TABLE ItemTable (key TEXT UNIQUE ON CONFLICT REPLACE, value BLOB NOT NULL ON CONFLICT FAIL)
@Derin Nope, what if "username" actually exists, but the stored value is false ?
|
80

This method worked for me:

if ("username" in localStorage) { alert('yes'); } else { alert('no'); } 

5 Comments

this is the best option, in my opinion, as it distinguishes between whether a value has been set and whether it may be false/falsey.
This solution gives false positives for keys like length. The accepted answer is the correct way to solve this problem.
I like this solution. It's clean.
The accepted solution didn't work. Although yours, was completely a life saver! Thank you :-)
This method will work most of the time, but will catch you out one day. Run localStorage.__proto__ in the development console and you will see the properties that will conflict.
39

Update:

if (localStorage.hasOwnProperty("username")) { // } 

Another way, relevant when value is not expected to be empty string, null or any other falsy value:

if (localStorage["username"]) { // } 

6 Comments

It's short for if( localStorage["username"]==undefined )
Not quite - it's a short for if (localStorage["username"]==undefined || localStorage["username"]==0 || localStorage["username"]==null || localStorage["username"]==false || localStorage["username"]=='') @AllanRuin
@oriadam Not quite; you both got it backwards. It's short for if (localStorage["username"]!==undefined && localStorage["username"]!==0 && localStorage["username"]!==null && localStorage["username"]!==false && localStorage["username"]!=='')
@JoL lol you're right :) I'm updating the answer
This method seems better because it just checks for the key without needlessly returning the key value, e.g., if (localStorage.getItem(key) === null)
|
19

The MDN documentation shows how the getItem method is implementated:

Object.defineProperty(oStorage, "getItem", { value: function (sKey) { return sKey ? this[sKey] : null; }, writable: false, configurable: false, enumerable: false }); 

If the value isn't set, it returns null. You are testing to see if it is undefined. Check to see if it is null instead.

if(localStorage.getItem("username") === null){ 

4 Comments

Right, I answered to Thrustmaster above. But it doesn't work better with this :/
@Gabriel — In your comment above you are comparing the typeof the value to null. You need to compare the actual value.
Or use == instead of === because (for some weird reason) null==undefined is true. Then again, you don't need anything, like @Derin answered, you can simply if (localStorage["username"])

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.