Skip to content Skip to sidebar Skip to footer

Apparently Contradictory Behavior Of Javascript Function

The following function proposed by 'Doug Crockford: JavaScript: The Good Parts.' works great. var fibonacci = function () { var memo = [0, 1]; var fib = function (c) { cons

Solution 1:

It's a problem with Chrome's console output. Chrome seems to dynamically update the output to reflect the content of the array somehow. If you run it in Firebug, the output is:

[0, 1]    3 undefined
[0, 1]    2 undefined
[0, 1]    1 1
[0, 1]    0 0
[0, 1, 1] 1 1
2

Also it makes sense when you try to go through the code in your head: console.debug is the first statement in fib. The first time fib is called, memo is [0, 1] as there haven't been made any changes to the array. c is 3, so you get undefined. So in the first invocation, memo cannot be [0, 1, 1, 2] no matter what the console shows.

Some JavaScript consoles seem to show such a behaviour (in one way or an other), when you log references to arrays or objects. In these cases it is often better to set breakpoints and go through the code step by step.

Update: It seems Firebug fixed this issue (if it ever existed), but it still seems to exist in Firebug light.


Post a Comment for "Apparently Contradictory Behavior Of Javascript Function"