-1

Javascript does not throw up errors when I forget to use var to declare a variable. Much time was lost debugging because of careless mistakes like these.

What are the best practices to avoid forgetting using var to declare variable in Javascript?

I hope Stack Overflow users do not close this question too soon or downvote it too much since there is no definite answer. It is a problem that is affecting newbies like me.

guagay_wk
  • 26,337
  • 54
  • 186
  • 295
  • 5
    using [jslint](http://www.jslint.com/). Unfortunately there isn't a single opinion on that so this question is _still_ likely to get closed. – AD7six May 27 '14 at 08:12
  • 1
    I'm using reSharper in Visual studio that is helps. Otherwise you can use http://www.jslint.com/ – Alex Char May 27 '14 at 08:12
  • 1
    Also, there are errors on the console, if you're using Chrome or Firefox. – John Bupit May 27 '14 at 08:14
  • Your question is like "How not to forget a language?", the answer is "Just speak it!", write code and use static analysis tools. – micnic May 27 '14 at 08:16
  • 1
    Perl has `use strict;` to do exactly this. Javascript also has `use strict;` but I think it does something else. – Thilo May 27 '14 at 08:16
  • Missing var is not always a mistake, Javascript actually declares variables with or without using var keyword, the difference comes in their scope, read this for more info http://stackoverflow.com/questions/1470488/what-is-the-function-of-the-var-keyword-in-ecmascript-262-3rd-edition-javascript – Mustafa sabir May 27 '14 at 11:00

1 Answers1

4

Add "use strict" to the top of your js files. This will make it impossible to accidentally declare global variables. e.g.

"use strict";
mistypedVaraible = 17; // throws a ReferenceError

More detail is available on the mozilla developer network - Strict mode

Linting tools such as jshint / jslint would also go some way to checking the quality of your code. You could even use a task runner such as Grunt (or Gulp, Broccoli, etc) to automate the process, so that your code is checked every time it is changed.

The Sample Gruntfile walks you through an example which would watch, jshint, and concatinate your final build file (amongst other things)

RYFN
  • 2,939
  • 1
  • 29
  • 40