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.
Table of Content
- Understand the Coding Style in JavaScript
- Name Conventions for Variables and Functions
- Proper Use of Indentation and Line Spacing in JavaScript Coding Style
- How to Handle Comments in JavaScript Code
- Use the Semicolons and Braces Correctly in JavaScript
- JavaScript Code Formatting Tools
- Examples of Coding Style in JavaScript
- Wrapping Up
- FAQs
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 unclearJavaScript 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?
- 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?
- Use camelCase for variables
- Keep 2 spaces for indentation
- Always use semicolons
// Example of camelCase
let userName = "Ali";
// Example of indentation
function greet() {
console.log("Hello");
}
How to follow JavaScript coding style automatically?
ESLintchecks coding style errorsPrettierformats 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 runs code in different ways, but the for loop stays one of the most common tools. You use it…
The ternary operator in JavaScript keeps your code short. It helps you write conditions inside one line. JavaScript lets you…
Math.random() gives a number between 0 and 1 in JavaScript. It helps create random values for colors or other data.…
JavaScript Ninja Code points to ways that help a person write code that runs fast and stays easy to read.…
JavaScript gives you the Math.trunc() function to work with decimal numbers. You use it when you want to remove the…
JavaScript object methods are simple ways to handle data inside objects. An object can hold many values, and methods give…
AJAX keeps your web app fast. You do not need to reload the page every time you send or get…
Unary operators in JavaScript work with only one value. They can change, test, or change the type of that value,…
The development of full-featured and interesting pages cannot be done without JavaScript which makes it possible to animate plain HTML…
JavaScript gives you the Math.round() function to deal with decimal numbers. You use it when you want to round a…