Search code examples
javascriptsession-storage

javascript null comparison different on chrome and firefox


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.


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."