1

I'm running a simple test and i get a strange behaviour, here is the js code:

 var handler = function(index,params){

    params.id = index;

}

function test(){
    var params = {'id':0};
    console.log(params);
    gradualRepetitionCalls(0,10,params);
}



function gradualRepetitionCalls(index, maxIndex,params) 
{
    if (index < maxIndex) 
    {
        handler(index,params);
        index++;

        gradualRepetitionCalls(index,maxIndex,params);
    }
}

test();

The strange thing is that the console.log(params) shows that the id is '9' while i would expect it to be '0'. Is console.log() asynchronous?

2
  • A shorter test case would be: var a = {'id': 0}; console.log(a); a.id = 1; Commented Aug 26, 2012 at 9:06
  • This is taken from a much more complex function and simplified for the question purposes, that is why it is structured like this. Commented Aug 26, 2012 at 9:19

2 Answers 2

3

Well, your code snippet is overly complex, try this:

var params = {id: 0};
console.log(params);
params.id = 1;

In Firefox it shows:

Object { id=0 }

but when I click on an object to drill down, it show id=1. In Google Chrome it just shows Object, but id=1 when drilled down.

The reason for this odd behaviour is that console understand that you are logging an object (not just a string) and every time you look at the console or refresh it, it display the current state of that object.

If you find this behaviour error-prone and counter-intuitive, here are some workarounds:

console.log(JSON.stringify(params));
console.log(params.id);

Also note that this is how JavaScript debuggers work, it's not JavaScript's fault per se.

Sign up to request clarification or add additional context in comments.

Comments

2

No, console.log is synchronous. But you create only one object and "output" this object to the console - after that, you alter the properties of this object (objects are passed by reference!). The console just shows the recent state of this object, not a snapshot from the point of time when it has been logged.

1 Comment

but this is counter intuitive, when i console.log the object i expect it to log the current state not the state after the script ended. Also, if i log it inside the loop it will show me the same objet 9 times, but if i log just the id it shows the correct id for each iteration???

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.