mc9
mc9

Reputation: 6349

Memory leak when defining a variable

I would like to know why jsLint is complaining that I might be leaking a variable when defining some variables like this:

var foo = bar = {};

It says I might be leaking bar.

My hunch is that it is because bar is global variable. Then, how can I assign foo and bar to point to the same object in one line? JavaScript won't let me write:

var foo = var bar = {};

Or is the issue something else?

Upvotes: 1

Views: 186

Answers (3)

Barmar
Barmar

Reputation: 780889

The reason it's complaining about "leaking a variable" is because you're only declaring the local variable foo. bar is not being declared, it's just being assigned, so this creates a global variable. Your statement is equivalent to:

var foo = (bar = {});

which is short for:

bar = {};
var foo = bar;

Written that way, you can see that there's no declaration of the bar variable. If you want to declare multiple variables in a single var statement, you must separate them with commas:

var bar = {}, foo = bar;

Or you can write them as separate statements:

var bar = {};
var foo = bar;

You could also separate the declarations and assignments:

var foo, bar;
foo = bar = {};

Upvotes: 2

Beri
Beri

Reputation: 11610

Best approach would be :

var foo = {} , bar = {};

But foo and bar would refer to two different objects.

If you want them to refer to the same object, then:

var foo = {}, bar = foo;

Upvotes: 2

Cerbrus
Cerbrus

Reputation: 72857

You have 2 options:

var foo = {},
    bar = {};

Or:

var foo, bar;
foo = bar = {};

The first one creates individual objects for foo and bar.
In the second example, both foo and bar point to the same object.

You can't (/shouldn't try to) declare and assign multiple variables using a single var statement, and a single object literal, on one line. Then you're just declaring multiple variables that point to the same object.

Upvotes: 2

Related Questions