JavaScript Coding Style, Error handling

Shihab Ahmed
3 min readMay 6, 2021

JavaScript Coding Style

Code must be as clean for an easy read as possible.

Syntex: Here is a cheat sheet with some suggested rules (see below for more details):

Curly Braces:

avoid one-line code. If you want one line code to remove curly braces.

Example:

var number = 5 ;
if (number === 5 ) consle.log(‘Five’);

Line Length:

Nobody likes to read long conditions. Best practice split them,

Example:

Function Placement:

If you are writing many functions and also code uses them there are three ways to organize the functions

  1. Declare the functions then write the code

Example:

2. Declare the function below the code

3. Mixed:

A function is declared where it's first used.

JavaScript Error Handling — try…catch

Syntex:

try..catch

How to try..catch work:

  1. Firstly executed the code in try{…}
  2. If any error find then executed the code in a catch (err){…}
  3. If there are no errors then skip the catch(err){…}
  4. try…catch only works for runtime error
  5. try…catch works synchronously

try…catch Error object:

When an error occurs JavaScript generates an object.

catch:

  • name — error name
  • message — error textual message
  • stack — current call stack

Example:

Returns-> ReferenceError: hello is not defined

Returns-> ReferenceError

Returns->

ReferenceError: hello is not defined
at Object.<anonymous> (G:\Me\Medium\javascript\index.js:2:5)
at Module._compile (internal/modules/cjs/loader.js:1063:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
at internal/main/run_main_module.js:17:47

--

--