WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

JavaScript Best Practices


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


Avoid Global Variables

Use as few global variables as possible.

It includes all data types, objects, and functions.

Global variables and functions can be overwritten by other scripts.


Always Declare Local Variables

All factors utilized in a capacity ought to be announced as local factors.

Local factors must be pronounced with the var keyword, else they will end up worldwide variables.

Declaration at the top

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

The benefits of doing this are:

  • Get cleaner code
  • A good place to find local variables
  • Easier to avoid unwanted global variables
  • Reduce the possibility of unwanted redeclarations
/Declare at the beginning
var firstName, lastName, value, rebate, fullPrice;

//Use later
firstName = "John";
lastName = "Doe";

price = 19.90;
rebate = 0.10;

fullPrice = cost * 100/discount;

Can also be used for loop variables:

/Declare at the beginning
var i;

//Use later
for (I = 0; I < 5; i++) {

Initialize Variables

It is good practice to initialize variables when you declare them.

The benefits of doing 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 = ();

Never Declare Number, String, or Boolean Objects

Always treat numbers, strings, or booleans as crude qualities. Not as objects.

Declaring these sorts as articles, backs off execution speed, furthermore, produces dreadful side effects:

Example

var x = "John";             
var y = new String("John");
(x === y)/is false on the grounds that x is a string and y is an article.
Try it Yourself »

Or even worse:

Example

var x = new String("John");             
var y = new String("John");
(x == y)/is false in light of the fact that you can't analyze objects.
Try it Yourself »

Don't Use new Object()

  • Use {} rather than new Object()
  • Use "" rather than new String()
  • Use 0 rather than new Number()
  • Use false rather than new Boolean()
  • Use [] rather than new Array()
  • Use/()/rather than new RegExp()
  • Use work (){} rather than new Function()

Example

var x1 = {};          /new object
var x2 = "";          /new crude string
var x3 = 0;           /new crude number
var x4 = false;       /new crude boolean
var x5 = [];          /new cluster object
var x6 =/()/;        /new regexp object
var x7 = function(){}; //new capacity object
Try it Yourself »

Beware of Automatic Type Conversions

Be aware that numeric values can be accidentally converted to strings or NaN (Not a Number). JavaScript is a loose type. Variables can contain different data types, and variables can change their data type:

Example

var x = "Hello";     //typeof x is a string
x = 5;               //changes typeof x to a number
Try it yourself »

If you do mathematical operations, JavaScript can convert numbers to strings:

Example

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

Subtracting a string from a string will return no NaN (Not a Number) without error

Example

"Hello" - "Dolly"   /returns NaN
Try it Yourself »

Use === Comparison

== Comparison operators always typecast (to match types) before comparison.

=== The operator forces comparison of values and types:

Example

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

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

Use Parameter Defaults

If a parameter is missing when the function is called, the value of the missing parameter is set to undefined .

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

Example

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

Read increasingly about capacity parameters and contentions at Function Parameters


End Your Switches with Defaults

Always end your switch explanations with a default. Regardless of whether you think there is no requirement 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 »