Question

I have the following code:

var a=sessionStorage.getItem("Token");  
alert(a==null);

The returned value is null (If I alert(a) it displays null). The problem is that the alert(a==null) display is TRUE on firefox and FALSE on safari and chrome. WTH? I have tried a===null with the same results as well as !a.

What am I doing wrong or what am I not aware of?

Thanks for any help.

Was it helpful?

Solution

You said in a comment: "I set Token with sessionStorage.setItem("Token",null);"

I believe the problem is that you are supposed to use session storage to store strings. When you pass null to setItem() it converts it to a string "null". Then when you retrieve it with getItem() you get back this string "null" which is of course not equal to an actual null value.

You can see this behaviour here: http://jsfiddle.net/CWVww/1/

If you want to remove a previously set item then do this:

sessionStorage.removeItem("Token");

...and then calls to .getItem("Token") will return null.

I don't know why Firefox behaved differently. From the MDN page on session storage: "Keep in mind that everything you store in any of the storages described in this page is converted to string using its .toString method before being stored."

OTHER TIPS

Your code worked perfectly with me (tested on Chrome). However, I suggest you to use the ! operator and also check the type of the current value:

var a = sessionStorage.getItem("Token");
if(!a && typeof a!=='string'){        //a doesn't exist
    //Do something
}else{        //a does exist
    //Do something
}

The operator ! will return true either when a is null or undefined.

You could try String(a) == "null". However, if the value of the Token item is set to "null" (the string "null") the code won't work as expected, so we have to add another condition:

var a = sessionStorage.getItem("Token");
if(String(a)==="null" && typeof a!=="string"){        //a doesn't exist
    //Do something
}else{        //a does exist
    //Do something
}

This way, the condition will return true when the "stringified" value of a is "null" and the type of the a var is not string

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top