Javascript variables to innerHTML – Can't figure out where this "undefined" is coming from

I’m passing a "log" back and forth between game players via AJAX calls.

The first player takes their turn and it’s logged, the log is saved into the local object, then when they save the loc.log is written to the game.log. The next player gets the game object and adds game.log to their log. For some reason when the 2nd player loads it though an "undefined" is added to the start of it. Then when the 1st player reloads it there are 2 in a row, undefinedundefined. I can’t figure out why. Everything seems to be defined.

Here’s my code:

let loc = {log: ""}
let game = {log: ""};

function gameLog(message) {

    let dateTime = new Date().toLocaleString();
    let logMessage = '<i>' + dateTime + '</i><br>' + message + '<br><br>';
    $('log').insertAdjacentHTML('afterbegin', logMessage);
    loc.log = logMessage + loc.log;
}

function save() {
    game.log = loc.log;
}

function load(){
    $('log').innerHTML = game.log + $('log').innerHTML;
}

8 thoughts on “Javascript variables to innerHTML – Can't figure out where this "undefined" is coming from”

Leave a Comment