JavaScript Best Practices - Code Like a Pro (Pt. 2)

JavaScript Best Practices - Code Like a Pro (Pt. 2)

Beginners Series Episode 3 😁🥂

Hey! Have you seen our Beginners Series Episodes? You can check it out Here.

Check every week for new content in this series to help you demystify some terms around web development and programming with JavaScript

Okay! Back to the second part of JavaScript Best Practices. In this episode, we will continue on the best practices to follow while writing your JavaScript codes.

1. Use Shortcut Notations

How about keeping your code as simple, as readable and performing the same function as possible? Yeah, you can use shortcut notations or shorthand notations as others call them to reduce the number of lines and characters in a block of code or function. This is a best practice to adopt while writing quite lengthy code or you want to keep things simple.

There are several examples to show some of the shortcut notations used in JavaScript and these include:

Arrays

Long

var lunch = new Array();
lunch[0]='Dosa';
lunch[1]='Roti';
lunch[2]='Rice';
lunch[3]='what the heck is this?';

Shortcut

var lunch = [
   'Dosa',
   'Roti',
   'Rice',
   'what the heck is this?'
];

Conditional Statements

Long

const x = 20;
let answer;
if (x > 10) {
    answer = "greater than 10";
} else {
    answer =  "less than 10";
}

Shortcut

const x = 20;
const answer = x > 10 ? "greater than 10" : "less than 10";

Using Arrow Functions

Long

function sayHello(name) {
  console.log('Hello', name);
}

setTimeout(function() {
  console.log('Loaded')
}, 2000);

list.forEach(function(item) {
  console.log(item);
});

Shortcut

sayHello = name => console.log('Hello', name);

setTimeout(() => console.log('Loaded'), 2000);

list.forEach(item => console.log(item));

You can find out more about shortcut notations here or here

2. Use Comments Well Often

“Good code explains itself” is an arrogant myth.

The JavaScript comments are a meaningful way to deliver message. It is used to add information about the code, warnings or suggestions so that the end user can easily interpret the code. Also, code that you do not want to run can be commented on as it gives others insight into what you are trying to achieve

Comment what you consider needed - but don’t tell others your life story. Avoid using the single-line comment // for multiple lines of code. /* */ is much safer to use because it doesn’t cause errors when the line break is removed.

3. Avoid heavy nesting

Nesting code explains its logic and makes it much easier to read, however nesting it too far can also make it hard to follow what you are trying to do. Readers of your code shouldn’t have to scroll horizontally or suffer confusion when their code editors wrap long lines.

The other problem of nesting is variable names and loops. As you normally start your first loop with i as the iterator variable, you’ll go on with j,k,l and so on. This can become messy quite quickly:

function renderProfiles(o){
  var out = document.getElementById(‘profiles’);
  for(var i=0;i<o.members.length;i++){
    var ul = document.createElement(‘ul’);
    var li = document.createElement(‘li’);
    li.appendChild(document.createTextNode(o.members[i].name));
    var nestedul = document.createElement(‘ul’);
    for(var j=0;j<o.members[i].data.length;j++){
      var datali = document.createElement(‘li’);
      datali.appendChild(
        document.createTextNode(
          o.members[i].data[j].label + ‘ ‘ +
          o.members[i].data[j].value
        )
      );
      nestedul.appendChild(datali);
    }
    li.appendChild(nestedul);
  } 
  out.appendChild(ul);
}

As I am using the generic variable names ul and li here, I need nestedul and datali for the nested list items. If the list nesting were to go even deeper I would need more variable names, and so on and so on. It makes more sense to put the task of creating nested lists for each member in its own function and call this with the right data. This also prevents us from having a loop inside a loop. The addMemberData() function is pretty generic and is very likely to come in handy at another time. Taking these thoughts on board, I would rewrite the code as follows:

function renderProfiles(o){
  var out = document.getElementById(‘profiles’);
  for(var i=0;i<o.members.length;i++){
    var ul = document.createElement(‘ul’);
    var li = document.createElement(‘li’);
    li.appendChild(document.createTextNode(data.members[i].name));
    li.appendChild(addMemberData(o.members[i]));
  } 
  out.appendChild(ul);
}
function addMemberData(member){
  var ul = document.createElement(‘ul’);
  for(var i=0;i<member.data.length;i++){
    var li = document.createElement(‘li’);
    li.appendChild(
      document.createTextNode(
        member.data[i].label + ‘ ‘ +
        member.data[i].value
      )
    );
  }
  ul.appendChild(li);
  return ul;
}

4. Use [] Instead of new Array()

When defining or assigning new arrays, always resist the prompt to use the new Array() method. Why? Let's look at these code illustrations:

Okay

var a = new Array();
a[0] = "Joe";
a[1] = 'Plumber';

Better

var a = ['Joe','Plumber'];

Using the more verbose method: new Array() does have one extra option in the parameters: if you pass a number to the constructor, you will get an array of that length. There is no difference when you initialize an array without any length. So var a = [] & var b = new Array() is same. But if you initialize an array with length like var a = new Array(3);, it will set the array object's length to 3 while var a = [3]; will have an a.length=1;. This will be problematic whenever you do array_object.push, it adds item after last element & increase length for new Array() constructor, making the array length 4 and undefined indexes. The constructor method is therefore verbose and might cause unnecessary breaks in our code. Using the literal method [] is a best practice.

var b = new Array(3);
b.push("hello world");
console.log(a.length); // print 4

vs

var a = [];
a.push("hello world");
console.log(a.length); // print 1

To illustrate the difference between the two styles:

var a = [],            // these are the same
var   b = new Array(),   // a and b are arrays with length 0

var   c = ['foo', 'bar'],           // these are the same
var    d = new Array('foo', 'bar'),  // c and d are arrays with 2 strings

// these are different:
var    e = [3]             // e.length == 1, e[0] == 3
var   f = new Array(3),   // f.length == 3, f[0] == undefined

5. Use {} Instead of new Object()

Sequel to the above examples on using array literals instead of a constructor, it is also a good practice to use object literals when defining objects instead of the constructor. Here is an illustration

Okay

var obj1 = new Object();  
obj1.Name = "A Person";  
obj1.TelNo = "12345";

Better

var obj2 = {Name:"A Person",TelNo="12345"};

The function new Object will get re-declared every time an instance of this object is created. Alas, this won’t be optimized away - you’ll have the function several times in memory, for each instance you’ve created.

For this reason, many prefer to always use the object literal syntax and never use the Object constructor. While there are no performance differences between the two approaches, the byte savings and conciseness of the object literal form is what has made it the de facto way of creating new objects. ES Lint.

6. Use JSLint

JSLint is a debugger written by Douglas Crockford. It is used to catch errors in the development environment while writing JavaScript code. It can be installed on mostly all code editors and it scans for any noticeable issues and errors in your code before running it on clients(browsers).

"JSLint takes a JavaScript source and scans it. If it finds a problem, it returns a message describing the problem and an approximate location within the source. The problem is not necessarily a syntax error, although it often is. JSLint looks at some style conventions as well as structural problems. It does not prove that your program is correct. It just provides another set of eyes to help spot problems." - JSLint Documentation

Before signing off on a script, run it through JSLint just to be sure that you haven't made any careless mistakes.

Conclusion

Hello devs, wrapping up on this episode, we will return next week with the Part 3 and the last episode of JavaScript Best Practices. While we wait, it will be great to research more on these, try them out on our new projects and give constructive feedback on the content in general in the comment section.

Some articles referenced here for more clarity are:

Code Like a Pro till the next episode 🥂😁.