JavaScript Coding Style and Comments (Best Practice)
As a programmer /developer, our code must be as clean and easy to read. We need to write comments to understand the codes for others.
Coding Style
function pow(num, sup) {
let result = 1; for (let i = 0; i < sup; i++){
result *= number;
}
return result;
}let num= prompt("x?", "");
let sup= prompt("n?", "");if(num < 0) {
alert(`${num} is not valid,
please enter a non-negative integer number`);
} else {
alert( pow(num, sup) );
}
Curly Braces
Bad practice of writing JavaScript code:-
if (n < 0) {alert(‘${num} is not valid’);}
or,
if (n < 0)
alert(‘${num} is not valid’)
or,
if (n < 0) alert(‘${num} is not valid’);
Best practice to use Curly Braces:-
if (n < 0) {
alert(‘${num} is not valid’); // 2 space indentation
}
Line Length
Long Horizontal code is bad. It’s very irritating for code readers.
const str = “JavaScript is a lightweight, interpreted, or just-in-
in if
statement:
if ( num !== condition1 && sup ≥ 0 && num ≥ 1 ) {
return pow(num, sup);
}
You need to split the long code.
const str = `JavaScript is a lightweight, interpreted, or
just-in-time compiled programming language
with first-class function`;
for if
statement:
if (
number !== condition1 &&
super ≥ 0 &&
number ≥ 1
) {
return pow(num, sup);
}
Code Indentation
There are two types of Code Indentation.
1. Horizontal Code Indentation
2. Vertical Code Indentation
Horizontal Indents: 2 or, 4 spaces for horizontal indentation is best practice for writing code.
for (let i = 0; i < sup; i++){
result *= number; // 2 spaces
}
or,
for (let i = 0; i < sup; i++){
result *= number; // 4 spaces
}
Vertical Indents: Splitting the code into logical blocks using empty lines
function pow(num, sup) {
let result = 1;
for (let i = 0; i < sup; i++){
result *= number;
}
return result;
}
Semicolons
You must need to use a semicolon after each code statement.
let num = prompt(“x?”, “”);
let sup = prompt(“n?”, “”);
Nested Code
Always Try to avoid Nesting code too many levels deep.
You can use the continue or, return keyword to avoid nested code.
use of continue keyword
for(let i = 0; i < n; i++) {
if(i % 2 === 0) {
// code
}
}
Avoid nesting with continue keyword:-
for(let i = 0; i < 10; i++) {
if(i % 2 === 0) continue;
// code
}
use of return keyword
function pow(num, sup) {
if (num < 0) {
console.log('Please Enter Positive Number!');
} else {
let result = 1; for (let i = 0; i < sup; i++){
result *= num;
}
return result;
}
}
avoid nesting using the return keyword
function pow(num, sup) {
if (num < 0) {
console.log('Please Enter Positive Number!');
return;
}
let result = 1; for (let i = 0; i < sup; i++){
result *= num;
}
return result;
}