Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrong value in console.log [duplicate]

Possible Duplicate:
Is Chrome's JavaScript console lazy about evaluating arrays?

I have the following snippets in javascript whose output makes me feel that something is going wrong.

1.

a=2;
console.log(a);
a+=2;
console.log(a);

Output:2 4 ; as expected

2.

t=[0,2];
console.log(t);
t[0]+=2;
console.log(t);

Output: [2,2] [2,2]

Shouldn't the output be [0,2] [2,2] ? And whats the difference between the above two cases that results in the different answers in both the cases?

like image 864
gopi1410 Avatar asked Jun 26 '12 19:06

gopi1410


People also ask

Does console log equal print?

The only notable difference between the two is that, when printing an object, console. log gives special treatment to HTML elements, while console.

How do I check the value of console logs?

Steps to Open the Console Log in Google Chrome With the Chrome browser open, right-click anywhere in the browser window and select Inspect from the pop-up menu. By default, the Inspect will open the "Elements" tab in the Developer Tools. Click on the "Console" tab which is to the right of "Elements".

Does console log return anything?

console. log(A); Parameters: It accepts a parameter which can be an array, an object or any message. Return value: It returns the value of the parameter given.

Is console log same as return?

console. log() is a function used to print information to the console. return on the other hand is a call to pass some value back up to where the call was made.


2 Answers

It's because the log is delayed until Chrome has time to do it (i.e. your scripts releases the CPU).

Try this to understand what happens :

var t=[0,2];
console.log(t);
setTimeout(function() {
     t[0]+=2;
   console.log(t);
}, 1000);

It outputs what you expect.

Is that a bug of Chrome ? Maybe a side effect of an optimization. At least it's a dangerous design...

Why is there a difference ? I suppose Chrome stores temporarily what it must log, as a primary (immutable) value in the first case, as a pointer to the array in the last case.

like image 132
Denys Séguret Avatar answered Oct 18 '22 00:10

Denys Séguret


console.log in chrome/ff is asynchronous and objects that are logged are interpreted at the time when they're expanded. . Instead make a copy of the object if you want to see its value at that time (for an array):

t=[0,2];
console.log(t.slice(0));
t[0]+=2;
console.log(t);

With an array, calling .slice will duplicate the array and not create a reference. I wouldn't suggest using a time out: this really doesn't solve the problem, just circumvents it temporarily.

like image 28
zamnuts Avatar answered Oct 18 '22 01:10

zamnuts