JavaScript Coding Style
As a programmer, our code must be clean and organized. This is the art of coding. I will talk here about the fundamental javaScript coding style. Let’s start.
Primitive Values
Primitive values in javaScript are strings, numbers, null, undefined, and so on. Use a single quote when declaring a string, not double-quote or caret sign. Don’t write a string in multiple lines, try to keep it in one line. And must use a semicolon.
const str = 'Hello world';//not
const str = "Hello world";
//or
const str = `Hello world`;
Curly Braces in Function or If Else
Curly Braces is a common thing in our coding when we use a function or if-else condition. In JavaScript language, curly braces are written in Egyptian style where it starts in one line and has white space before starting. Some beginners programmer write it in a new line, that’s not an appropriate style of writing Curly Braces.
//Wright
if (condition) {
//do somethimg
}//bad
if (condition) {//do somethimg}
Indentation
In javascript coding has two types of indent one is Horizontal indent and another is Vertical indent. In horizontal indent use 2 or 4 spaces. Most programmer use tab for horizontal indent.
function doIt(foo) {
//4 spaces
}
and in vertical indent use one empty line.
function doIt(foo) {
let n = 3;
//1 empty line
if (n > 0) {
//do something
}
//1 empty line
return foo;
}
Function Placement
There are three ways to organize the functions and the code that uses them. Firstly, write functions first then codes.
function doSomething(foo) {
//.....
}function toDo(foo) {
//.....
}const work = doSomething(foo);
toDO(work);
Secondly, write the code first then functions.
const work = doSomething(foo);
toDO(work);function doSomething(foo) {
//.....
}function toDo(foo) {
//.....
}
Lastly, write the function where it first uses.
Comment
In JavaScript language, we can write a comment in two ways. For single-line comment we use (//) this, and for multiline comment use (/* … */) this. If need to write a single line comment write the comment above the subject of the comment. Using so much comment in code is not a good thing.
//your comment
let active = true;