Skip to content Skip to sidebar Skip to footer

Javascript Var Hoisting Issue

I have a very simple Javascript function that hits a MS SQL server and returns some records back. There is a cell that i want to only display in the top table row when it is uniqu

Solution 1:

Take the "var" off the var termcounter = rs(0);

You're probably right about hoisting--JavaScript doesn't have block scope, so both times you declare termcounter it's in the same scope. This is a very common mistake, since JavaScript looks like C-based languages which have block scope.

Declaring a var in a conditional or looping block is equivalent to declaring it at the beginning of the function that block is in, scope-wise.

You'll lose less hair if you always place your var declarations at the top of functions--never in conditional or loop blocks. See Crockford. You can use JSLint to warn you. (Oh, by the way, you're missing a ton of semicolons--JSLint will hurt your feelings.)

So why are you redeclaring it? Drop the second "var" and just do the assignment.


The Microsoft stuff is alien to me, but I find the rs(0) syntax baffling. Is rs an object? Or is there some kind of magic that makes it into a function as well (you never know with JS)? I did some Googling and I wonder if you need to be using rs.fields(0) or rs.fields(0).name or rs.fields(0).value or something.

Solution 2:

You have this:

var termcounter = rs(0);

I don't think you want to be redeclaring it here - remove the var:

termcounter = rs(0);

Solution 3:

Post a Comment for "Javascript Var Hoisting Issue"