javascriptif-statementsessionstorage

If...Else, Else block isn't executing when the if condition isn't satisfied


I'm struggling to figure out why my else block isn't executing although the if block will execute if the condition is satisfied i'm relatively new to java-script but i have programming experience and i am slightly baffled as to why it wont.

This is the function that is called on $(document).ready:

function selectSchool()
    {
        alert("Selecting a School!" + sessionStorage.sCData);
        if (!sessionStorage.sCData || sessionStorage === NULL)
        {
            alert("Its Empty!");
        } else {
            alert("Its Not Empty!");
            //$('#schoolDropdown').val(sessionStorage.sCData);
            //sessionStorage = NULL;
            alert('Session Storage: ' + sessionStorage.sCData);
        }
        alert("Function finished");

    };

i am struggling to see any bad syntax but im not too great with javascript with the amount of experience i have with it, i commented out the two lines just too see if it was anything thats happening in them lines that were causing it to not execute adding alerts() to see where the function is able to get to.

Thanks in advance for any help you can give.


Solution

  • I would switch the condition and check for truthyness of sessionStorage and if sCData is truthy as well.

    function selectSchool() {
        alert("Selecting a School!" + sessionStorage.sCData);
        if (sessionStorage && sessionStorage.sCData) {
            alert("Its Not Empty!");
            alert('Session Storage: ' + sessionStorage.sCData);
        } else {
            alert("Its Empty!");
        }
        alert("Function finished");
    };