Avoid Global Variables
Minimize the use of global variables.
This includes all data types, objects, and functions.
Global variables and functions can be overwritten by other scripts.
Use local variables instead, and learn how to use closures.
Always Declare Local Variables
All variables used in a function should be declared as local variables.
Local variables must be declared with the var keyword, otherwise they will become global variables.
Strict mode does not allow undeclared variables.
Declarations on Top
It is a good coding practice to put all declarations at the top of each script or function.
This also goes for loop variables:
It is a good coding practice to initialize variables when you declare them.
Initializing variables provides an idea of the intended use (and intended data type).
Never Declare Number, String, or Boolean Objects
Always treat numbers, strings, or booleans as primitive values. Not as objects.
Declaring these types as objects, slows down execution speed, and produces nasty side effects:
Or even worse:
Don't Use new Object()
Beware of Automatic Type Conversions
Beware that numbers can accidentally be converted to strings or NaN (Not a Number).
Subtracting a string from a string, does not generate an error but returns NaN (Not a Number):
Use === Comparison
The == comparison operator always converts (to matching types) before comparison.
The === operator forces comparison of values and type:
Use Parameter Defaults
If a function is called with a missing argument, the value of the missing argument is set to undefined.
Undefined values can break your code. It is a good habit to assign default values to arguments.
End Your Switches with Defaults
Always end your switch statements with a default. Even if you think there is no need for it.
Avoid Using eval()
The eval() function is used to run text as code. In almost all cases, it should not be necessary to use it.
Because it allows arbitrary code to be run, it also represents a security problem.