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 with Function Guide: Syntax with Examples

JavaScript has a statement called "with" that changes how code accesses object properties. The"with" Function makes a temporary scope, so…

JavaScript Math tan: The Tangent of an Angle in Radians

JavaScript Math.tan() finds the tangent of an angle in radians. You use it when you need to solve angle-based math.…

Data Types in JavaScript: Primitive and Non-Primitive

Data types in JavaScript help hold values and shape code rules. They set clear plans for text, numbers, and other…

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…

JavaScript Class and Object Constructors with Examples

Object constructors and class constructors in JavaScript create objects in a structured way. Both provide methods to build reusable code.…

JavaScript toSorted Function Guide with Examples

This guide shows how toSorted function works in JavaScript with arrays. It covers syntax, rules, and examples for numbers, text,…

JavaScript Hoisting: How It Works with Examples

You will face hoisting early when you write JavaScript. It affects how your code runs, and it may confuse you…

JavaScript While Loop: How It Works with Examples

The JavaScript while loop runs code as long as a condition stays true. You can use it to repeat tasks…

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…

JavaScript math.exp: How to Calculate e^x

Math.exp is a built-in JavaScript function that returns the value of e raised to a given number. Here, e is…

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.