Search code examples
javascriptfancytree

Javascript variable values changing between two console.log() lines


I'm using Fancytree, and I'm creating a new node using the ExtEdit extension. The title (main text) of the node appears to be set correctly, but the value consistently changes between two console.log() statements and the wrong value is being sent to the server.

What's going on here? This is boggling my mind.

Here's the FancytreeNode API.

This is the full function I'm using:

function createNode(data) {
    console.log('this is the data object');
    console.log(data);
    console.log('this is data.node.title');
    console.log(data.node.title);
    $.ajax({
        method: 'post',
        data: {
            name: data.node.title,
            parentId: data.node.parent !== undefined ? data.node.parent.key : null
        },
        url: '/my/url'
    }).success(function (thisData, status, jqXHR) {
        data.node.key = thisData.id;
    });
}

This is the output. Notice how data.node.title is different.

Mind-boggling result


Solution

  • I was able to figure it out from the comment by Nevosis. When an object is logged using console.log(), it is not actually evaluated--it's only a reference. The Fancytree event that causes the function to fire acts a little strangely; data.node.title isn't set to the new value until the event finishes, but I wasn't expanding the object in the console until after that point. data.node.title when logged directly is evaluated (because it has to be), which is why the value was different. I was able to see the correct data object by setting a breakpoint immediately after that console.log().