JavaScript Best Practices

We've covered several introductory concepts for JavaScript programming in this course and how to debug your code. We'll review some coding guidelines and best practices you'll use as a JavaScript developer to ensure consistency, readability, security, and accessibility. Read this article to learn about some of the best practices for developing programs.

Functions and objects


Function naming

For function names use lowerCamelCasing, and use concise, human-readable, semantic names where appropriate.

Do this:

function sayHello() {
  alert('Hello!');
};

Not these:

function SayHello() {
  alert('Hello!');
};

function notVeryObviousName() {
  alert('Hello!');
};


Defining functions

Where possible, use the function declaration to define functions over function expressions:

Do this:

function sum(a, b) {
  return a + b;
}

Not this:

let sum = function(a, b) {
  return a + b;
}

When using anonymous functions inside a method that requires a function as a parameter, it is acceptable (although not required) to use an arrow function to make the code shorter and cleaner.

So instead of this:

const array1 = [1, 2, 3, 4];
let sum = array1.reduce(function(a, b) {
  return a + b;
});

you could write this:

const array1 = [1, 2, 3, 4];
let sum = array1.reduce((a, b) =>
  a + b
);

Also bear in mind:

  • There should be no space between a function name and its opening parenthesis.
  • There should be a space between the parentheses and the opening curly brace.

Creating objects

Use literals – not constructors – for creating general objects (i.e., when classes are not involved):

Do this:

let myObject = { };

Not this:

let myObject = new Object();


Object classes

Use ES class syntax for objects, not old-style constructors.

For example:

class Person {
  constructor(name, age, gender) {
    this.name = name;
    this.age = age;
    this.gender = gender;
  }

  greeting() {
    console.log(`Hi! I'm ${this.name}`);
  };
}

Use extends for inheritance:

class Teacher extends Person {
  ...
}


Object naming

When defining an object class (as seen above), use UpperCamelCasing (also known as PascalCasing) for the class name, and lowerCamelCasing for the object property and method names.

When defining an object instance, either a literal or via a constructor, use lowerCamelCase for the instance name:

let hanSolo = new Person('Han Solo', 25, 'male');

let hanSolo = {
  name: 'Han Solo',
  age: 25,
  gender: 'male'
}