JavaScript style guide

When you follow the style guidelines for a language that you are working with, the code becomes more readable and maintainable.

Let’s go over some guidelines for Javascript from the Google JavaScript Style Guide:

Naming conventions

  • Class, record, interface, and typedef names are written in UpperCamelCase.
  • Method names are written in lowerCamelCase.
  • Parameter names are written in lowerCamelCase.
  • Local variable names are written in lowerCamelCase.
  • Constants are written in UPPERCASE.
// class name in UpperCamelCase
class MyClass {
  // Class methods in lowerCamelCase
  constructor() { ... }
  // Parameters in lowerCamelCase
  methodOne(numberOne) { ... }
}
// Local variable name in lowerCamelCase
let myVariable = 20;
// Constant in UPPERCASE
const PI = 3.142;

Formatting

  • Control structures (e.g., if, for, while, etc.) are surrounded by braces.
  • Spaces are used around operators (e.g., +, -) and after commas.
  • There is no line break before the opening brace, but there is a line break after the opening brace and a line break before the closing brace.
  • Each time a new block or block-like construct is opened, ​indent it with two spaces.
  • Each statement is followed by a line-break.
  • Every statement must be terminated​ with a semicolon.
  • Lines should be no longer than 80 characters.
// Braces around the control structure for.
// Spaces around the operators
// Line break after the opening and closing curly brace
for(int i = 0; i < 10; i++){
  // Statement indented by two spaces.
  console.log("Hello World!");
}

Object literals

  • Object literals (comma-separated key-value pairs ) may represent either structs (with unquoted keys and/or symbols) or dicts (with quoted keys). Mixing these two in a single object is invalid.
  • Use an object literal, { }, instead of the object constructor.
// Using the { } object literal
let country = {
  // Using unquoted keys only
  Name: "Singapore",
  Area: 721.5,
};

Variable declarations

  • Use let when a variable needs to be reassigned and const otherwise. Do not use var.
  • Every variable declaration declares only one variable.
// Using let because myVar needs to be reassigned late
// Moreover, only one variable is declared per line
let myVar = 10;
let anotherVar = 19;
myVar = 20;
// Using const because welcome does not need to reassigned.
const welcome = "Hello";

Refer to the Google JavaScript Style Guide for more details.

Copyright ©2024 Educative, Inc. All rights reserved