JavaScript Coding Style Guide for Beginners

javascript coding style

JavaScript code follows some rules that help both new and old developers. A project without rules in code creates trouble for teams that must fix or add new parts.

Understand the Coding Style in JavaScript

A coding style in JavaScript shows how a person writes code in a fixed way. It sets rules for names, space, comments, and symbols. The whole team can follow the same path when a project has a style.

The purpose of coding style is to make code easy to read and share. It lets one developer read the work of another developer without much effort. It also saves time when a project grows with new code parts.

A fixed coding style reduces mistakes that come from mixed rules. It also saves time when people must read long code parts. A team that follows one style can build new features fast and fix issues fast.

Name Conventions for Variables and Functions

Variables in JavaScript often use camelCase. A name like userName shows both words in one short term. Functions also follow camelCase, such as getData.

Classes must use PascalCase, for example UserAccount. These rules give clear signals for each type in code.

Here is an example:

// Variables use camelCase
let userName = "John";
let totalPrice = 250;
let isActive = true;

// Functions also use camelCase
function getData() {
  return "Sample Data";
}

function calculateTotal(price, tax) {
  return price + tax;
}

// Classes use PascalCase
class UserAccount {
  constructor(name, balance) {
    this.name = name;
    this.balance = balance;
  }
}

class ProductList {
  constructor(items) {
    this.items = items;
  }
}

Proper Use of Indentation and Line Spacing in JavaScript Coding Style

Indentation makes code blocks stand apart from one another. Each block should move four spaces or two spaces from the left side.

For example:

function loginUser(username, password) {
    if (username === "admin" && password === "1234") {
        console.log("Login successful");
    } else {
        console.log("Login failed");
    }
}

// Extra line separates functions
function registerUser(username, email) {
    let user = {
        name: username,
        email: email
    };

    console.log("User registered:", user);
}

Extra lines between blocks help the eyes to see where one block ends.

How to Handle Comments in JavaScript Code

Comments explain parts of the code that may look hard at first sight. Short comments use // while long notes use /* */. Comments must not repeat what the code already says, but must show why a step exists.

Here is an example:

// Check login before access
function loginUser(username, password) {
    if (username === "admin" && password === "1234") {
        console.log("Login successful");
    } else {
        console.log("Login failed");
    }
}

/*  
   Store user data after registration.  
   We keep both name and email in one object  
   so that later we can send notifications easily.  
*/
function registerUser(username, email) {
    let user = {
        name: username,
        email: email
    };

    console.log("User registered:", user);
}

Use the Semicolons and Braces Correctly in JavaScript

Each JavaScript line should end with a semicolon to avoid mix-up. Curly braces must wrap code blocks that start after if(any condition syntax) or for(any loop syntax). Wrong use of braces or missed semicolons can break the code run.

Here’s an example that shows the correct use of semicolons and braces:

let userName = "John";  
let age = 25;  

if (age >= 18) {
    console.log(userName + " is an adult.");
} else {
    console.log(userName + " is a minor.");
}

for (let i = 0; i < 3; i++) {
    console.log("Count: " + i);
}

while (age < 30) {
    age++;
    console.log("Age is now: " + age);
}

And here’s a wrong version that can cause errors:

let userName = "John"   // Missed semicolon
let age = 25  

if (age >= 18)          // No braces, only runs first line
    console.log(userName + " is an adult.")
    console.log("This runs always, not inside if!")  // Wrong

for (let i = 0; i < 3; i++) // Missed braces
    console.log("Count: " + i)  // Hard to track

while (age < 30) age++  // One-liner, unsafe and unclear

JavaScript Code Formatting Tools

Many tools can help set one style across a project. Prettier is a tool that changes code into the same format.

ESLint checks if code follows set rules and warns when code breaks the style.

Examples of Coding Style in JavaScript

Function with Consistent Indent:

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

This example shows a function with two lines that move inward by two spaces. It also shows how a function should use a clear name.

Class with PascalCase:

class UserProfile {
  constructor(name) {
    this.name = name;
  }
}

This example shows a class that starts with a capital letter. The constructor assigns a value to the class and keeps the code style clean.

Use of Comments:

// Check if user is active
if (user.isActive) {
  console.log("User is active");
}

This example shows a short comment that explains the purpose of the line.

Semicolon Use:

let age = 25;
let name = "Tom";
console.log(name + " is " + age + " years old");

This example shows each line that ended with a semicolon. The code runs safely because it avoids mistakes that can come from missed semicolons.

Wrapping Up

In this tutorial, you learned how to follow JavaScript rules to write code. Here is a quick recap:

  • You should use semicolons at the end of each statement.
  • You have to use correct names for functions and variables with prefixes as much as you can.
  • Keep proper indentation and spaces based on the code structure.

FAQs

What is JavaScript coding style and why use it?

JavaScript coding style means a set of rules to write code clearly.
  • It improves team work
  • It reduces bugs
  • It makes code readable

// Bad style
var num= 10; function test(){console.log(num)}

// Good style
var num = 10;
function test() {
  console.log(num);
}

What are common JavaScript coding style rules?

Some rules define spacing, naming, and function blocks.
  1. Use camelCase for variables
  2. Keep 2 spaces for indentation
  3. Always use semicolons

// Example of camelCase
let userName = "Ali";

// Example of indentation
function greet() {
  console.log("Hello");
}

How to follow JavaScript coding style automatically?

You can use tools to check and fix code style.
  • ESLint checks coding style errors
  • Prettier formats code automatically

// Install ESLint
npm install eslint --save-dev

// Run ESLint
npx eslint script.js

// Install Prettier
npm install prettier --save-dev

Similar Reads

JavaScript for Loop: How to Iterate Arrays by Examples

JavaScript runs code in different ways, but the for loop stays one of the most common tools. You use it…

How to Use the Ternary Operator in JavaScript

The ternary operator in JavaScript keeps your code short. It helps you write conditions inside one line. JavaScript lets you…

JavaScript Math.random() Returns Numbers 0–1

Math.random() gives a number between 0 and 1 in JavaScript. It helps create random values for colors or other data.…

JavaScript Ninja Code for Beginners

JavaScript Ninja Code points to ways that help a person write code that runs fast and stays easy to read.…

JavaScript Math trunc: How to Removes Decimals

JavaScript gives you the Math.trunc() function to work with decimal numbers. You use it when you want to remove the…

JavaScript Object Methods with Examples

JavaScript object methods are simple ways to handle data inside objects. An object can hold many values, and methods give…

What Is AJAX? How It Works in Web Development with Examples

AJAX keeps your web app fast. You do not need to reload the page every time you send or get…

JavaScript Unary Operators: How they Work with Examples

Unary operators in JavaScript work with only one value. They can change, test, or change the type of that value,…

JavaScript: How to Add JS to HTML

The development of full-featured and interesting pages cannot be done without JavaScript which makes it possible to animate plain HTML…

JavaScript Math round(): How It Works With Examples

JavaScript gives you the Math.round() function to deal with decimal numbers. You use it when you want to round a…

Previous Article

PHP sizeof: How to Count Elements in Arrays with Examples

Next Article

HTML Link Attributes Guide for Beginners

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *


Subscribe to Get Updates

Get the latest updates on Coding, Database, and Algorithms straight to your inbox.
No spam. Unsubscribe anytime.