4

When I run this code:

var a = ['a','b','c'];
var b = ['a','b','c'];

for(i = 0; i <= a.length-1; i++){
    b.shift();
    console.log(b);
}

I expected this output:

['b','c']
['c']
[]

But I get this output:

[]
[]
[]

Why?

And how do I get my expected output?

Cato Johnston
  • 44,131
  • 10
  • 39
  • 42
  • I do get your desired output.. I guess the console.log isn't a console.log in your current code. – Johan Dec 26 '11 at 12:13
  • I'm getting the exact output you expect with the same code – Nabab Dec 26 '11 at 12:13
  • Your code is working correctly for me. What you've specified as expected output is exactly what i get when i run your code from Firebug console. In Chrome console, i'm getting the same output as what you're getting. So looks like an issue in Chrome? – techfoobar Dec 26 '11 at 12:14
  • Hmm.. Interesting.. Looks like Chrome's console.log caches the output and flushes it out together after the loop! If you do a shift() and log (not in the loop), you'll get the correct output. But if you put it in a loop, it prints out the final value of b in all three cases! – techfoobar Dec 26 '11 at 12:16
  • It's a webkit "issue" with console.log, there are other references to it here on so. Another "fix" is to use tostring() in your log – J. Holmes Dec 26 '11 at 12:18

3 Answers3

8

This is a known problem in Chrome. It's because the console.log doesn't make a copy of what you want to display, it just stores the reference.

As the log isn't updated immediately, but once your function ends and the browser updates the user interface, the log will show the current state of the b variable, not the state when each console.log call was made.

To get the desired ouput you would have to make a flash copy of the state of the variable for each console.log call:

console.log(b.toString());
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
1

This is a side-effect of the console.log statements not being printed as the statements are executed. Note that if you replace your console.log with alert, the code works as expected.

Jon Newmuis
  • 25,722
  • 2
  • 45
  • 57
0

Or change the log paramater to be an expression as per my answer to Javascript Funky array mishap

console.log ('' + b);
Community
  • 1
  • 1
HBP
  • 15,685
  • 6
  • 28
  • 34