Sunday, May 13, 2018

JavaScript Style Guide and Coding Conventions

Always use the same coding conventions for all your JavaScript projects.

JavaScript Coding Conventions
Coding conventions are style guidelines for programming. They typically cover:

  • Naming and declaration rules for variables and functions.
  • Rules for the use of white space, indentation, and comments.
  • Programming practices and princiles
Coding conventions secure quality:
  • Improves code readability
  • Make code maintenance easier
Coding conventions can be documented rules for teams to follow, or just be your individual coding practice.


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 products nasty side effects:


Use === Comparison

The == comparison operator always converts (to matching types) before comparison.
The === operator forces comparison of values and type:

Example

0 == "";        // true1 == "1";       // true1 == true;      // true
0 === "";       // false1 === "1";      // false1 === true;     // false
Try it Yourself »

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.

Example

function myFunction(x, y) {
    if (y === undefined) {
        y = 0;
    }
}
Try it Yourself »
Read more about function parameters and arguments at Function Parameters

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.

No comments:

Post a Comment