1

When I test this code snippet in jsFiddle with JSLint, it gives me this strange warning:

Problem at line 3 character 10: Cannot set property 'first' of undefined

But if I declare the variable currentNumber outside of (i.e. before) the for-loop, it doesn't complain.

What is the reason of this?

helpermethod
  • 59,493
  • 71
  • 188
  • 276
  • You're showing the wrong fiddle. Your currently linked fiddle is valid, and doesn't contain a `.first` property setter. – Rob W Oct 26 '11 at 20:42
  • @Rob W While it executes (and doesn't contain a first property), if you click the JSLint button, it still shows the error. – helpermethod Oct 26 '11 at 20:45
  • It does not complain in Firefox 7.0.1., what browser is it complaining in? – Caimen Oct 26 '11 at 20:54
  • 1
    I have only reproduced this error in Chrome 14, not Firefox 3.6.23. – Rob W Oct 26 '11 at 20:55

2 Answers2

3

Looks like a bug in jsFiddle or JSLint, honestly... If I try for (var i = 0; i < 10; ++i) {} it gives the same error. If I take out var it stops complaining.

mergeconflict
  • 8,156
  • 34
  • 63
  • Yep, see: http://stackoverflow.com/questions/4646455/jslint-error-move-all-var-declarations-to-the-top-of-the-function/6411669#6411669 – Lee Kowalkowski Oct 26 '11 at 21:17
  • How is that a bug? This is exactly what JSLint claims to do. – Jere Oct 26 '11 at 21:26
  • @Jere no, the correct error report should be `move 'var' declarations to the top of the function`, not `cannot set property 'first' of undefined`. – mergeconflict Oct 26 '11 at 21:32
  • Ok, agreed that the error wording is wrong, just not that no error should occur. – Jere Oct 26 '11 at 21:33
2

JSLint will want var declarations at the top of functions. The particular error you're getting in jsfiddle is odd, but a complaint from JSLint isn't unexpected at all.

Problem at line 3 character 6: Move 'var' declarations to the top of the function.

http://www.jslint.com/

Warning!

JSLint will hurt your feelings.

...

The var statements should be the first statements in the function body.

Community
  • 1
  • 1
Jere
  • 3,377
  • 1
  • 21
  • 28
  • +1 Is this a widely accepted practice? I know that variables in JS have function scope but still this seems very weird to me. – helpermethod Oct 27 '11 at 07:36
  • 1
    Using the var keyword is of course very important because you usually don't want to bleed into the global scope. As far as putting all var declarations at the top, that's a personal choice and JSLint seems to think it's a good idea obviously. It might be easier to easily identify all the local variables in a function, but to me that's just silly. I'd rather have variables declared when they are needed, close to the relevant code. Especially for loop variables... it doesn't do anyone any good to see a var i; at the top of a function. – Jere Oct 27 '11 at 11:56