JavaScript code: error handling, code style & comments

Asfakur Rahman
6 min readMay 6, 2021
  1. Error Handling

Error is the most common thing in any type of programming. When an error occurs in programming, that program won’t able to give user output & it will show up what’s the reason that occurs an error in the program.

If there is an error in the code, it immediately terminates the code in the compiler and shows that error in the console.

“try…catch” syntax

There is a syntax called “try…catch”, that allowed a user to catch an error that can do something more than instead of terminating the program.

The “try” statement gives the user to test a part of his code for errors & the “catch” statement gives the user to handle a part of the code. There is other 2 statement “throw” and“ finally”. The “throw ”statement gives the user for creating a custom error. The “finally” statement for executing the whole code after try and catch execute the whole code regarding the result.

The “try…catch” statement syntax are here:

try{
// code...
}
catch (err) {
// error handling
}

here is a flow-chart of the “try…catch” statement:

fig 1.1: “try…catch” statement flow-chart.

In this flow-chart, we clearly see that after beginning the code when using the “try” statement, if there is no error then the code ignores the catch block. If there is an error occurs, then it ignores the rest of the “try” statement & executes catch block.

Here is an example with no errors:

try{
alert('the begining of try runs here'); // no errors
alert('the ending of try runs here'); // no errors
}
catch (err) {
alert('Here catch is ignored, cause there is no error at all');
}

Here is an example with errors:

try{
alert('the begining of try runs here');
iamman; // error, this variable is not defined!
alert('the ending of try runs here (never able to reached)');
}
catch (err) {
alert('Error has been occured');
}

“try…catch” statement works only for runtime error

If user want to run “try…catch” statement to work, the code that user used this statement must be executable/runnable & it should be valid javascript code. It won’t able to work if the code is syntactically wrong:

try{
({}).{
} catch (err) {
alert("The engine can't able to understand this code, this is invalid");
}

“try…catch” statement works in synchronously

If an exception happens in a scheduled code like a “setTimeout” function, then “try..catch” can’t able to catch that error & code can’t able to work:

try {
setTimeout(function(){
iamman;// script will be terminated here
}, 900);
}
catch (err) {
alert("invalid, won't able to work");
}

Error object

When an error occurs in code, JavaScript generates an object that containing information about it. Then the object is passed as an argument to “catch” statement:

try{
//...
}
catch (err) {// <--- the "error object", replace with another word instead of err
//...
}

For the all built-in-errors, the “error” object has two main properties:

  1. name

2. message

Optional “catch” binding

If user don’t need any type of error info, then the “catch” statement may remove it:

try{
//...
}
catch{// <-- without (err) function
//...
}

Using “try…catch” statement

Let’s go with a real life example, Javascript supports the “JSON.parse(str)” method that used to get the decode data that recieved over the ntework . Here is an example of JSON.parse:

let json = '{"name":"Niloy", "age": 26}'; // data from the server  let user = JSON.parse(json); // convert the text representation to Javascript object  
// now user is an object with properties from the string
alert( user.name ); // Niloy
alert( user.age ); // 26

If the “JSON.parse” method is not correct, it generates an error:

let json = “{ wrong json }”;
try {
let user = JSON.parse(json);
alert( user.age ); // doesn’t work
} catch (err) {
alert( err.name );
alert( err.message );
}

Throwing own errors

Sometimes json is syntactically absolutely right but don’t have a required “name” property. Here you can see:

let json = '{ "age": 23}'; // incomplete data  
try {
let user = JSON.parse(json); // <-- no errors
alert( user.name ); // no name!
}
catch (err) {
alert( "doesn't execute" );
}

try…catch…finally

the “finally” statement is the last statement after try & catch. If try & catch statement has no errors, then the “finally” statement will work properly. Here is the syntax of “finally”:

try {    
... try to execute the whole code ... }
catch (err) {
... handling errors ...
} finally {
... execute full code ...
}

2. Coding Style

For all types of code in any type of language, it must have to be cleaner & readable for everyone. The art of programming to take a complex task and code it in a way that is both correct and human-readable. A good code style is always granted for all perspectives.

Here is a diagram with some suggested rules of coding:

fig 1.2: Some rules for coding

Curly Braces

In most of the JavaScript projects curly braces are written in a “Egyptian” style with the opening brace on the same line as the corresponding keyword. There should also be a space before the opening bracket, Here is an example:

if (i > 2) {
alert(` i is greater than 2`);
}

Line length

There is no need to create a big line that is too long horizontally. So needs to split them & it’s a good practice. Here is an example:

let str= `
my name is Asfakur Rahman,
i am a now studied in B.sc in CSE at NUB,
now i am increasing my developing skill.
`;

Indents

There are 2 types of indents usually used in codes

  1. Horizontal indents:

Example:

cast(one,
two, // 5 spaces padding at the left
three,
four,
five
) {
// ...
}

2. Vertical indents:

Example:

function power(a, n) {
let res = 1;
for (let i = 0; i < n; i++) {
res *= a;
}
return res;
}

Semicolons

A semicolon should needs to be placed after each statement. There are several languages where a semicolon is truly optional and it is rarely used. In JavaScript though, there are cases where a line break is not interpreted as a semicolon, leaving the code vulnerable to errors.

Function Placement

There are 3 different ways that a user use function in a code.

  1. Declare the functions top of the code that uses them:

Example:

// function declarations
function createElement() {
...
}

function setHandler(elmnt) {
...
}

function walkThrough() {
...
}

// the code which uses function
let elmnt = createElement();
setHandler(elmnt);
walkThrough();

2. At first use code, after that use function:

Example:

// the code that uses the functions
let elmnt = createElement();
setHandler(elem);
walkThrough();


function createElement() {
...
}

function setHandler(elmnt) {
...
}

function walkThrough() {
...
}

3. Mixed: Where’s the function is used first, there is a function declared.

From this 3 types, number 2 is usually used most of the time.

3. Comments

Comments in code are basically used for why and how the code works. This comments can be single-lined comments or be muli-lined comments. For single-lined comments, starting with // & for multi-lined comments, /*……. */ .

Single-lined comments Example:

// Changing heading:
document.getElementById("myHead").innerHTML = "My First Heading";

// Changing paragraph:
document.getElementById("myPara").innerHTML = "My first Paragraph.";

Multi-lined comments Example:

/*
This code will change
the heading with id = "myHead"
and the paragraph with id = "myPara"
in my web page:
*/
document.getElementById("myHead").innerHTML = "My First Heading";
document.getElementById("myPara").innerHTML = "My first Paragraph.";

--

--