Categories
JavaScript Best Practices

JavaScript Best Practices — Using Libraries and Shortcuts That are Clear

Spread the love

Like any other programming language, JavaScript has its own list of best practices to make programs easier to read and maintain. There are a lot of tricky parts to JavaScript, so there are things we should avoid that reduce the quality of our code. By following best practices, we can create elegant and manageable code that’s easy for anyone to work with.

In this article, we look at using libraries, using shortcuts that make sense, short ways to build a string from an array, and being aware of the difference between development and live code.

Use Libraries When They Exist

If somebody already made a library to do something that we want to do, we should use the library instead of writing everything from scratch again.

Reinventing the wheel is a time-consuming process, then testing all the cases takes even longer.

This means that we should use libraries to speed up software development and not reinvent the wheel.

Nowadays, client-side apps are more complex than ever, with users expecting slick user experiences in the apps we write. This means writing everything from scratch is pretty much impossible.

This is why frameworks like Angular, React and Vue are becoming more and more popular. There’s no going back to the bad old days where everything is written in plain JavaScript.

Front end development isn’t just adding a few things on top of our back end apps anymore.

However, when we’re learning JavaScript, we should still learn by writing plain JavaScript code first to learn the principles that make these libraries and framework work.

Nowadays, client-side apps are complex enough that it’s hard to avoid using lots of libraries to build something functional.

Difference Between Development Code and Live Code

The codebase that we read and write shouldn’t be mistaken for the code that’s run.

Most browsers optimize the code if we follow the best practices that are listed all over the online community.

Browsers convert the code we write to machine code on run-time to make it run faster.

Also, lots of client-side apps now have a build process associated with it to optimize the code by minifying it and combining redundant code into one place, etc.

This means that we should build code for readability and maintainability rather than trying to make hard to read code that we think will make it run faster.

Browsers no longer run code line by line from script files anymore.

Use Shorthand When They Make Sense

Some of the older shorthands in JavaScript are confusing. For example, if we run the following code:

if(false)  
   var x = false  
   let y = 0  
console.log(x, y)

We get undefined and 0 logged. undefined makes sense, but why is y 0? This is because the declaration of y actually doesn’t belong to the if block.

As we can see, the if statement without curly braces is confusing. Only the first line after the if statement is considered to be inside the if block.

Therefore, we should always wrap our if blocks with curly braces.

Another problem with the code snippet above is that we don’t have semicolons. This is another problem because when don’t know where the line ends. It’s better to just make it clear by putting in the semicolon at the end.

However, since ES6, we have lots of shorthands that are very useful and aren’t confusing.

For example, the spread and rest operators are very useful for copying or combining objects and getting arguments in an array respectively.

The spread operator can be used as follows:

const obj1 = { foo: 1, bar: 2 }, obj2 = { baz: 3 };  
const obj3 = { ...obj1, ...obj2 };

Then we get obj3 having the value:

{ foo: 1, bar: 2, baz: 3 }

The rest operator uses the same 3 dots, but works on functions. For example, we can write a function with the rest operator as follows:

const add = (a, b, ...rest) => {  
  return a + b + rest.reduce((a, b) => a + b, 0);  
}

Where ...rest is has an array with the arguments other than the first 2.

Then we can call it as follows:

console.log(add(1, 2));  
console.log(add(1, 2, 3));  
console.log(add(1, 2, 3, 4, 5));

And we get 3, 6, and 15 respectively.

Another handy and clear shortcut is the destructuring assignment syntax. It works on both objects and arrays. For example, we can destructure an array into variables as follows:

const [a, b] = [1, 2];  
console.log(a, b);

Similarly, with objects, we can write:

const {  
  foo,  
  bar  
} = {  
  foo: 1,  
  bar: 2  
};  
console.log(foo, bar);

We get 1 and 2 for a and b respectively in both examples.

Shortest Way to Building a String

There’re multiple ways to build a string from an array of strings in JavaScript. One way is to use a loop as follows:

const arr = ['foo', 'bar', 'baz'];  
let str = '';  
for (let i = 0; i < arr.length; i++) {  
  str += arr[i];  
  if (i !== arr.length - 1) {  
    str += ',';  
  }  
}

The other way is to use the join method built into array objects:

const arr = ['foo', 'bar', 'baz'];  
let str = arr.join(',');

As we can see, the loop is much more complex and are much more prone to errors because of it. We’ve to loop through the array, concatenate each entry, and then add a comma after it if it’s not the last entry.

On the other hand, the join method just joins the array entries with a comma with one line.

Today’s JavaScript apps are more complex than ever. This is why we should use libraries and frameworks to build apps to make our lives easier.

This also means that we should be writing code that makes development easy rather than thinking about how to accommodate browsers. However, we should still think about performance when writing the code.

Also, we should also use shortcuts that makes development and reading the code easy. Most shortcuts introduced with ES6 or later have both of these characteristics. Older shortcuts like writing if statements without curly braces are not.

Finally, we should use existing methods to simplify code. For example, when making a comma-separated string from an array of strings, we can use the join method instead of writing a loop to do it.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.