Javascript Best Practices

Blesed JosephBlesed Joseph
4 min read

These JavaScript best practices can help with enhanced performance, quicker page loads, more readable code, and simpler maintenance and debugging. Well-developed code can also aid in preventing security flaws and errors.

Avoid Global Variables

  • The use of global variables should be minimized

  • All data types, objects and functions are included here

  • Other scripts may overwrite global variables and functions

  • Instead, utilize local variables and become familiar with closures

Always Declare Local Variables

All variables used in a function should have their local variables specified. If neither the var nor the let or the const keyword is used, when a local variable is declared, it will be transformed into a global variable.

Declarations on Top

All declarations should be placed at the beginning of each script or function as good coding practice. This will result in:

  • A cleaner code

  • Give users a single location to look for local variables.

  • Reduce the likelihood of unwanted re-declarations

  • Make it simpler to avoid undesirable (implied) global variables.

Example:

Declare your variables at the beginning

// Declare at the begining 
let firstName, lastName, birthYear, currentYear, age

// Use later
firstName = 'Blessed';
lastName = 'Joseph';

birthYear = 1987;
currentYear = 2022;

age = currentYear - birthYear;

Initialize Variables

When you declare variables, you should always initialize them. This will:

  • Provide a cleaner code

  • Provide a single location for variable initialization.

  • Avoid using undefined values.

Declare Array with Const

Declaring arrays with const prevents accidental type changes

Example:

let cities = ['New York', 'Los Angeles', 'Chocago'];

cities = 3  // changes array to number
const cities = ['New York', 'Los Angeles', 'Chocago'];

cities = 3  // not possible

Don't Use new Object()

  • Instead of new String(), use " ".

  • Instead of new Number(), use 0

  • Instead of using new Boolean(), use false

  • Rather than new Object(), use {}

  • Instead of using new Array(), use [].

  • Instead of using new RegExp(), use /()/.

  • Instead of using new Function(), use function (){}.

Example:

let a = "";   // new primitive string
let b = 0;   // new primitive number
let c = false;   // new primitive boolean
const d = {};   // new object
const e = [];   // new array object
const f = /()/;   // new regexp object
const g = function(){};   // new function object

Beware of Automatic Type Conversions

  • JavaScript is a loosely typed language.

  • A variable can hold any type of data.

  • A variable's data type can be changed:

Example:

let c = 'Hello';  // typeOf c is string

c = 5; // changes typeOf c to a number

Use the === Comparison

Prior to comparison:

  • the == comparison operator converts (to types that match).

  • The === operator requires a value and type comparison:

Example:

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

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

Use Parameter Default

  • When a function is called with an unspecified argument, the value of the unspecified argument is set to undefined.

  • Undefined values can cause your code to fail. Assigning default values to arguments is a good practice.

Example:

function myFunction(a, b) {
    if (a === undefined) {
        a = 0;
    }
        }

Always End your Switches with Default

Always include a default at the end of your switch statements. Even if you believe it is unnecessary.

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'
}

Avoid Number, String, and Boolean as Objects

  • Numbers, strings, and booleans should always be treated as primitive values, not as objects.

  • Declaring these types as objects slows execution and has negative side effects:

Example:

let a = 'Blessed';
let b = new String ('Blessed');

(a == b)   // is false because typeOf a is 'string' and typeOf b is 'object'

Avoid Using eval()

  • The eval() function is used to run text as code. But in most cases, it should not be necessary to use it.

  • It also poses a security risk because it allows arbitrary code to be executed.

Was this post helpful to you?

Please like, save and share it with your friends to inspire them!

Follow me for more interesting coding tips and tricks

0
Subscribe to my newsletter

Read articles from Blesed Joseph directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Blesed Joseph
Blesed Joseph

Self-motivated IT professional with deep knowledge and proficiency in JavaScript, HTML, CSS, and mobile responsive website development, as well as highly potent skills and ability in encoding virus-free and efficient code, plus a very strong ability to execute and standard software architectural patterns.