0

Based on the description of the funcscope option in its documentation, it seems JSHint recognizes the utility of the variables being declared in "intended scopes" e.g. control structures etc. (even though in reality within a function in JS there is only one scope).

Why, then, does it throw up an error for the following, saying that i is declared multiple times?

if (condition) {
    var i = 1;
    //
}
else {
    var i = 2;
    //
}

Setting funcscope to either true or false does not help. Is there any way to suppress this error?

(I like having "logical/intended" variable scopes, and "defining" variables as close to where they are required. Helps me when code chunks need to be moved around.

EDIT: I know about variable hoisting. But I don't subscribe to Douglas Crockford's views on declaring all vars at the top of the function. That makes code harder to read, as well as harder to refactor when you have to move code snippets around. If you read the documentation of funcscope at the JSHint homepage, it also talks about intended scope, which is exactly what I am referring to as well. I am asking my question in this context)

Himanshu P
  • 9,586
  • 6
  • 37
  • 46

2 Answers2

1

You are doing it wrong. Your code is equivalent to writing:

var i;
var i; // duplicate!

if (condition) {
    i = 1;
} else {
    i = 2;
}

As you can see, you are defining i twice. I don't believe there is a flag to suppress that.

Evan Davis
  • 35,493
  • 6
  • 50
  • 57
  • I do know very well about variable hoisting, but I have tried to clarify what I mean on the original post. – Himanshu P Mar 25 '13 at 21:15
  • I understand what you're asking; what I'm saying is that you do not have a valid use case for _intended scope_. Declaring the same variable twice isn't just a problem of programming style, you are actually misusing the language. – Evan Davis Mar 25 '13 at 21:24
  • Hmm, I kinda get what you're saying. But to press my point further still, what is the *practical* problem with what I am doing, pedantry aside. OTH, if I don't do this, I have to use two different names even when they express the same idea. Or define a "common" variable at a "higher" scope, which creates the problems I noted in my original post. – Himanshu P Mar 25 '13 at 21:37
  • I suppose you have a point; it's an innocuous issue. I guess it's one of those things that, for me, it's such lazy programming, I don't believe there _should_ be a flag for it. Seems like JSHint agrees. – Evan Davis Mar 25 '13 at 22:08
-1

If you don't want to go with Douglas then how about

if (condition) {
    var i = 1;
    //
}
else {
    i = 2;
    //
}

Just remove the second var since you have already decalred var. You don't really need to declare var twice.

Chris Jones
  • 662
  • 2
  • 10
  • 23