Coding Standards - JavaScript Best Practices - Part 2

These articles will give you details on best practices for writing JavaScript code. JavaScript JQuery





This is part 2 for JavaScript standards. Previous 10 coding standards are present in part 1 of the article.

11. Always put spaces around operators ( = + - * / ), and after commas



var x = y + z;
var values = ["Volvo", "Saab", "Fiat"];



12. Always end a simple statement with a semicolon.


13. Global variables are written in UPPERCASE. Constants (like PI) written in UPPERCASE.


14. Hyphens can be mistaken as subtraction attempts. Hyphens are not allowed in JavaScript names.


15. Don't start names with a $ sign. It will put you in conflict with many JavaScript library names.


16. 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.


17. 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.


18. Declarations on Top

This will:

Give cleaner code

Provide a single place to look for local variables

Make it easier to avoid unwanted (implied) global variables

Reduce the possibility of unwanted re-declarations


19. Initialize variables when you declare them. Initializing variables provides an idea of the intended use (and intended data type).


var firstName = "",
    lastName = "",
    price = 0,
    discount = 0,
    fullPrice = 0,
    myArray = [],
    myObject = {};



20. Use === Comparison


0 == "";        // true
1 == "1";       // true
1 == true;      // true

0 === "";       // false
1 === "1";      // false
1 === true;     // false

Comments

Loading…

We use cookies and other technologies to improve your experience on our website and to analyze our traffic. By browsing our website, you consent to our use of cookies and other tracking technologies.

Accept cookies and close this message
Win now