JavaScript Best Practices

Please avoid global variables,new,===,eval()

Avoid global variables

Please use global variables as little as possible.

It includes all data types, objects, and functions.

Global variables and functions can be overwritten by other scripts.

Please use local variables instead and learn how to useClosure.

Always declare local variables

All variables used in the function should be declared asLocalVariables

Local variablesMustThrough var Declare with keywords, otherwise they will become global variables.

Strict mode does not allow undeclared variables.

Declare at the top

A good coding habit is to put all declarations at the top of each script or function.

The benefits of this are:

  • Get cleaner code
  • Provide a good location to find local variables
  • Easier to avoid unnecessary global variables
  • Reduce the possibility of unnecessary re-declaration
// Declare at the top
var firstName, lastName, price, discount, fullPrice;
// Used later
firstName = "Bill";
lastName = "Gates";
price = 19.90;
discount = 0.10;
fullPrice = price * 100 / discount;

It can also be used for loop variables:

// Declare at the top
var i;
// Used later
for (i = 0; i < 5; i++)  {

By default, JavaScript will move all declarations to the top (JavaScript hoisting).

Initialize variables

It is a good habit to initialize variables when you declare them.

The benefits of this are:

  • Cleaner code
  • Initialize variables in separate locations
  • Avoid undefined values
// Declare and initialize at the beginning
var firstName = "",
    lastName  = "",
    price = 0,
    discount = 0,
    fullPrice  = 0,
    myArray = [],
    myObject = {};

Variable initialization helps us understand the intended use and expected data type.

Please do not declare number, string, or boolean objects

Always consider numbers, strings, or booleans as primitive values, not objects.

If you declare these types as objects, it will slow down the execution speed and produce讨厌的副作用:

Example

var x = "Bill";             
var y = new String("Bill");
(x === y) // The result is false because x is a string and y is an object.

Try it yourself

Or even worse:

Example

var x = new String("Bill");             
var y = new String("Bill");
(x == y) // The result is false because you cannot compare objects.

Try it yourself

Please do not use new Object()

  • Please use {} instead of new Object()
  • Please use "" instead of new String()
  • Please use 0 instead of new Number()
  • Please use false instead of new Boolean()
  • Please use [] instead of new Array()
  • Please use /()/ instead of new RegExp()
  • Please use function (){} instead of new Function()

Example

var x1 = {};           // A new object
var x2 = "";           // A new primitive string value
var x3 = 0;            // A new primitive number
var x4 = false;        // A new primitive boolean value
var x5 = [];           // A new array object
var x6 = /()/;         // A new regular expression
var x7 = function(){}; // A new function object

Try it yourself

Be aware of automatic type conversion

Be aware that numbers can be unexpectedly converted to strings or NaN(Not a Number).

JavaScript is a loosely typed language. Variables can contain different data types, and variables can change their data type:

Example

var x = "Hello";     // typeof x is string
x = 5;               // Change typeof x to number

Try it yourself

If a mathematical operation is performed, JavaScript can convert numbers to strings:

Example

var x = 5 + 7;       // x.valueOf() is 12,  typeof x is number
var x = 5 + "7";     // x.valueOf() is 57,  typeof x is string
var x = "5" + 7;     // x.valueOf() is 57,  typeof x is string
var x = 5 - 7;       // x.valueOf() is -2,  typeof x is number
var x = 5 - "7";     // x.valueOf() is -2,  typeof x is number
var x = "5" - 7;     // x.valueOf() is -2,  typeof x is number
var x = 5 - "x";     // x.valueOf() is NaN, typeof x is number

Try it yourself

Subtracting strings with strings will not cause an error but will return NaN(Not a Number):

Example

"Hello" - "Dolly"    // Returns NaN

Try it yourself

Use === for comparison

== Comparison operators always perform type conversion before comparison (to match types).

=== The operator will force a comparison between values and types:

Example

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

Try it yourself

Using Parameter Defaults

If a parameter is missing when calling the function, the value of the missing parameter will be set to undefined.

undefined The value will break your code. It is a good habit to set default values for parameters.

Example

function myFunction(x, y) {
    if (y === undefined) {
        y = 0;
    }
}

Try it yourself

Please refer toFunction ParametersRead more about function parameters in this chapter.

to end the switch with default

Please use default to end your switch statement. Even if you think there is no need for it.

Example

switch (new Date().getDay()) {
    case 0:
        day = "Sunday";
        break;
    case 1:
        day = "Monday";
         break;
    case 2:
        day = "Tuesday";
         break;
    case 3:
        day = "Wednesday";
         break;
    case 4:
        day = "Thursday";
         break;
    case 5:
        day = "Friday";
         break;
    case 6:
        day = "Saturday";
         break;
    default:
        day = "Unknown";
} 

Try it yourself

Avoid using eval()

eval() Functions are used to allow text as code. In almost all cases, there is no need to use it.

Because it allows arbitrary code to run, it also means security issues.