I seem to be facing a common issue that many others have encountered. Despite my understanding that global variables can be modified inside functions in Javascript, I am struggling with this concept in practice.
var lastMessage = 0;
function loadChat() {
$.post("/lastmessage", { roomid: roomId })
.done(function(data) {
var response = JSON.parse(data);
if (response.state == "success") {
lastMessage = response.message;
console.log("Inside: " + lastMessage);
}
});
}
console.log("Outside: " + lastMessage);
After running the code snippet above, I get the following output:
Outside: 0
Inside: 17
While the value displayed inside the function is correct, the one outside of it remains unchanged. What could potentially be causing this discrepancy?