Hong Wang Hong Wang - 1 year ago 63
Javascript Question

Confusing JavaScript nested execution result

I try following simple JavaScript nested code, while the result is confusing.

Anyone can give a detail explanation? Thanks very much.

I am waiting...

// args = [];

function foo (param) {
args= [];
if (param <= 1) {
} else {
return param;


The final args is [], I guess the outer args (is [2]) is overwritten by the nested inner args (which is []). Who can give a detail explanation about the result? How is the execution sequences? Thanks.

Answer Source

From @Dmitry, thanks.

The args is a global binding (since you don't use var). In first call foo(1), you set it to:

args -----> [];

Then you add 2 to it by a recursive call. However, when you recursively call foo it rebinding global foo identifier to a new array in memory, still keeping the old one.

args -----> []  // new array

     -----> [] // old one

So you add 2 to the old one when return from recursion:

args -----> []  // new array

     -----> [2] // old one

After exit, args is bound to the new one which is empty, and the reference to the old one is missed (it will be GC'ed).

See binding and mutation topics: http://dmitrysoshnikov.com/ecmascript/es5-chapter-3-1-lexical-environments-common-theory/#name-binding

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download