I'm building an app using jQuery mobile but I have this problem where I call a function and assign a value within that function to a global var. When I try to log the var value to the console I get null. Then when I call the function again it displays the correct value. This is the code where have the problem:
var sessionId;
function startGame() {
    getGameSession();
    console.log(sessionId);
    /*
    if (sessionId != null) {
        loadGame();
    } else {
            displayMessage("Error", "Unable to load game");
    }
    */
}
function getGameSession() {
    var gameSession;
    $.ajax({
        type: "GET",
        url: "/answerIQ/index.php/get-game-session",    
        data: {},    
        success: function (data) {
            if (data.gameStatus == "success") {    
                sessionId = data.gameSession;
            } else {    
                displayMessage("Error", data.gameMessage);    
            }    
        },
        dataType: "JSON"
    });
}
 
    