My First Love — A True Love Story With JavaScript Unveiled

Anyone can’t forget their first love and my first love as a developer is with Javascript and had a long wish to write an article on some of the best practices and coding guidelines a scripting language which I ever love, indeed when I started as an intern web developer back in 2005, My job is to develop ASP (Active Server Pages) and JSP (Java Server Pages) applications without any IDE and use to develop using simple text editor like notepad so from those days I was bit crazy with Javascript and did lot of magics with the help of this little client side scripting language.

I still remember my first website www.adnoc.com (now moved to adnoc.ae) for one our Middle East customer which I had developed Front End as ASP pages (HTML+CSS+JavaScript with bit of server side code) where I believe written more than 400+ LOC in JavaScript post that within under less than a year we released 30+ web apps just written in Javascript. So Javascript is my beautiful Jaanu which I won’t ever forget.

As we all know, JavaScript is the number one programming language in the world, the language of the web, of mobile hybrid apps (like PhoneGap or Appcelerator), of the server side (like NodeJS or Wakanda) and has many other implementations. It’s also the starting point for many new developers to the world of programming, as it can be used to display a simple alert in the web browser but also to control a robot (using nodebot, or nodruino). The developers who master JavaScript and write organized and performant code have become the most sought after in the job market.

There’s no doubt that the JavaScript ecosystem changes fast. Not only are new tools and frameworks introduced and developed at a rapid rate, the language itself has undergone big changes with the introduction of ES2015 (aka ES6). Understandably, many resources have been written complaining about how difficult it is to learn modern JavaScript development these days.

In 2015, the sixth version of ECMAScript — the specification that defines the JavaScript language — was released under the name of ES2015(still often referred to as ES6). This new version included substantial additions to the language, making it easier and more feasible to build ambitious web applications. But improvements don’t stop with ES2015; each year, a new version is released.

Below I am listing some of the top 10 best practices and guidelines while coding in Javascript based on my own experience.

Declaring variables

JavaScript now has two additional ways to declare variables:let and const.
let is the successor to var . Although var is still available, let limits the scope of variables to the block (rather than the function) they’re declared within, which reduces the room for error:

// ES5
for (var i = 1; i < 5; i++)
{

console.log(i);

} // ← logs the numbers 1 to 4

console.log(i); // ← 5 (variable i still exists outside the loop)

// ES2015
for (let j = 1; j < 5; j++)
{

console.log(j);

}
console.log(j); // ← ‘Uncaught ReferenceError: j is not defined’

Using const allows you to define variables that cannot be rebound to new values. For primitive values such as strings and numbers, this results in something similar to a constant, as you cannot change the value once it has been declared:

const name = ‘Kobe’; name = ‘Uday’; // ← ‘Uncaught TypeError: Assignment to constant variable.’
// Gotcha
const person = { name: ‘Bill’ };
person.name = ‘Uday’; // person.name is now Uday.
// As we’re not changing the object that person is bound to, JavaScript doesn’t complain.

Arrow functions

Arrow functions provide a cleaner syntax for declaring anonymous functions (lambdas), dropping the function keyword and the return keyword when the body function only has one expression. This can allow you to write functional style code in a nicer way:

// ES5
var add = function(a, b) { return a + b; }
// ES2015
const add = (a, b) => a + b;
The other important feature of arrow functions is that they inherit the value of this from the context in which they are defined:
function Person()
{
this.age = 0;

// ES5
setInterval(function() {
this.age++; // |this| refers to the global object
}, 1000);

// ES2015
setInterval(() => {
this.age++; // |this| properly refers to the person object
}, 1000);

}

var p = new Person();

Create an object constructor

function Person(firstName, lastName){
this.firstName = firstName;
this.lastName = lastName;
}

var kobeMVP = new Person(“Kobe”, “Bryant”);

Be more cautious when using typeof, instanceof and constructor

typeof : a JavaScript unary operator used to return a string that represents the primitive type of a variable, don’t forget that typeof null will return “object”, and for the majority of object types (Array, Date, and others) will return also “object”.

constructor : is a property of the internal prototype property, which could be overridden by code.

instanceof : is another JavaScript operator that check in all the prototypes chain the constructor it returns true if it’s found and false if not.

var arr = [“a”, “b”, “c”];
typeof arr; // return “object”
arr instanceof Array // true
arr.constructor(); //[]

Improved Class syntax

If you’re a fan of object-oriented programming, you might like the addition of classes to the language on top of the existent mechanism based on prototypes. While it’s mostly just syntactic sugar, it provides a cleaner syntax for developers trying to emulate classical object-orientation with prototypes.

class Person
{
constructor(name)
{
this.name = name;
}
greet()
{
console.log(`Hello, my name is ${this.name}`);
}
}

Code linting

Linters are tools that parse your code and compare it against a set of rules, checking for syntax errors, formatting, and good practices. Although the use of a linter is recommended to everyone, it’s especially useful if you’re getting started. When configured correctly for your code editor/IDE, you can get instant feedback to ensure you don’t get stuck with syntax errors as you’re learning new language features.

You can check out ESLint, which is one of the most popular and supports ES2015+.

Modular Code

Modern web applications can have thousands (even hundred of thousands) of lines of code. Working at that size becomes almost impossible without a mechanism to organize everything in smaller components, writing specialized and isolated pieces of code that can be reused as necessary in a controlled way. This is the job of modules.

CommonJS modules

A handful of module formats have emerged over the years, the most popular of which is CommonJS. It’s the default module format in Node.js, and can be used in client-side code with the help of module bundlers, which we’ll talk about shortly.

It makes use of a module object to export functionality from a JavaScript file and a require() function to import that functionality where you need it.

// lib/math.js
function sum(x, y)
{
return x + y;
}
const pi = 3.141593
module.exports = { sum: sum, pi: pi };

// app.js
const math = require(“lib/math”);
console.log(“2π = “ + math.sum(math.pi, math.pi));

ES2015 modules

ES2015 introduces a way to define and consume components right into the language, which was previously possible only with third-party libraries. You can have separate files with the functionality you want, and export just certain parts to make them available to your application.

Here’s an example:
// lib/math.js
export function sum(x, y)
{
return x + y;
}
export const pi = 3.141593;

Here we have a module that exports a function and a variable. We can include that file in another one and use those exported functions:
// app.js
import * as math from “lib/math”;
console.log(“2π = “ + math.sum(math.pi, math.pi));

Or we can also be specific and import only what we need:
// otherApp.js
import {sum, pi} from “lib/math”;
console.log(“2π = “ + sum(pi, pi));

Create a Self-calling Function

This is often called a Self-Invoked Anonymous Function or Immediately Invoked Function Expression (IIFE). It is a function that executes automatically when you create it, and has the following form:

(function(){
// some private code that will be executed automatically
})();

(function(a,b){
var result = a+b;
return result;
})(10,20)

Generate a random set of alphanumeric characters

function generateRandomAlphaNum(len)
{

var rdmString = “”;
for( ; rdmString.length < len; rdmString +=Math.random().toString(36).substr(2));
return rdmString.substr(0, len);

}

Don’t use delete to remove an item from array

Use splice instead of using delete to delete an item from an array. Using delete replaces the item with undefined instead of the removing it from the array.

Instead of…

var items = [12, 548 ,’a’ , 2 , 5478 , ‘foo’ , 8852, , ‘Doe’ ,2154 , 119 ];
items.length; // return 11
delete items[3]; // return true
items.length; // return 11
/* items will be equal to [12, 548, “a”, undefined × 1, 5478, “foo”, 8852, undefined × 1, “Doe”, 2154, 119] */

Hope the above Javascript BestPractices and Coding Guidelines is helpful. Please feel free to reach out to me on borntowinuk@gmail.com if you need any additional information.

Enterprise Architect — Certified Cloud Specialist (Azure, Google, AWS and Alibaba), AI/AR SME, Cross Platform Mobile Development (React Native, Xamarin, iOS)