Variable leaking

140 views
Skip to first unread message

Joyston Colaco

unread,
Feb 20, 2015, 1:52:31 AM2/20/15
to jsh...@googlegroups.com
I have following code example
var a = b = c = d = 0;

When i run code through jsHint i get following error
 'column 23: You might be leaking a variable  here.'

Can anyone tel me what is the reason and how we can help this code?

Morten Sjøgren

unread,
Feb 20, 2015, 8:20:28 AM2/20/15
to jsh...@googlegroups.com
My guess is that it's because b, c, d and d will all be declared in the global scope.
In JavaScript (unless you're running in strict-mode) if you haven't declared your variables with var before you're assigning values to them, they'll be add to the global scope.
Example:
function aFn( ) {
   a = 1;
}

console.log( a ); /// throws error, not defined yet.
aFn( );
console.log( a ); /// 1

function bFn( ) {
   window.b = 1;
}

console.log( b ); /// throws error, not defined yet.
bFn( );
console.log( b ); /// 1

function cFn( ) {
   var c = 1;
}

console.log( c ); /// throws error, not defined yet
cFn( );
console.log( c ); /// throws error, not defined yet. c is a local variable in cFn's scope.

Vars are inheriated from parent scope (closure) 

var d = 0;
function dFn( ) {
   d = 1;
}

console.log( d ); /// 0
dFn( );
console.log( c ); /// 1

As for helping you with the code:
var a = 0, b = 0, c = 0, d = 0;
Or if you most (I find this very ugly):

var a, b, c, d;
Reply all
Reply to author
Forward
0 new messages