Like any kind of apps, JavaScript apps also have to be written well.
Otherwise, we run into all kinds of issues later on.
In this article, we’ll look at some best practices we should follow when writing JavaScript code.
Use {} Instead of New Object()
We should use object literals instead of new Object()
.
The constructor has no benefits over object literals and it’s longer.
Instead of writing:
let o = new Object();
o.name = 'james';
o.lastName = 'smith';
o.greet = function() {
console.log(this.name);
}
We write:
const o = {
name: 'james',
lastName = 'smith',
someFunction() {
console.log(this.name);
}
};
We can write:
const o = {};
to create an empty object.
Use [] Instead of New Array()
The Array
constructor is longer and doesn’t bring much benefit.
However, we can create an array with a given number of empty slots with it.
So we can use it with one numerical argument to create an empty array with the number of slots.
Other than that, we use array literals.
For example, instead of writing:
const a = new Array();
a[0] = "james";
a[1] = 'smith';
We write:
const a = ['james', 'smith'];
To create an empty with the Array
constructor, we write:
const a = new Array(10);
This creates an empty array with 10 slots.
Omit the Keyword and Use Commas Instead
If we have to declare a long list of variables, we can use commas to separate them.
For example, we can write:
let foo = 'some string',
bar = 'another string',
baz = 'one more string';
instead of:
let foo = 'some string';
let bar = 'another string';
let baz = 'one more string';
It’s shorter so it saves some typing.
Always Use Semicolons
We should use semicolons so that JavaScript won’t insert it for us.
This way, we can avoid errors.
So instead of writing:
const someItem = 'some string'
function foo() {
return 'something'
}
We write:
const someItem = 'some string';
function foo() {
return 'something';
}
“For in” Statements
If we’re using the for-in loop, we should use hasOwnProperty
to check if the property is a non-inherited property of the object we’re looping through.
For example, we can write:
for (let key in object) {
if (object.hasOwnProperty(key)) {
//...
}
}
We call hasOwnProperty
on the object with eh key
as the argument to check.
Use Timer Feature to Optimize Our Code
We can use the console.time
and console.timeEnd
function to check the timing of the code.
For example, we can write:
console.time("timer");
for (let x=5000; x > 0; x--) {}
console.timeEnd("timer");
The argument of both methods is the timer name. It’s used to identify when to start or end the timer.
Learn New Stuff
New JavaScript features come out every year.
They’re often useful features that we want to use.
So we should read often to keep up with them.
We can go to the MDN website to read about them.
Self-Executing Functions
We can make functions that run automatically when the page loads by wrapping functions with parentheses and then calling them.
For example, we can write:
(() => {
return {
name: 'james',
lastName: 'smith'
};
})();
We can create functions to return something.
Also, we can keep private variables inside them.
Raw JavaScript Can Always Be Quicker Than Using a Library
If something is available in plain JavaScript, then we should use that instead.
Browsers optimize the standard JavaScript library for speed.
So instead of using a 3rd party HTTP client, we may want to use the Fetch API.
Instead of using Lodash array methods, we can use built-in array methods.
JSON.Parse
JSON.parse
lets us parse JSON strings into JavaScript objects.
We can just use it on a JSON string by writing:
JSON.parse(jsonStr);
where jsonStr
is the string.
Remove Language and Type
If we’re including JavaScript scripts, we don’t need to add the language
and type
attributes.
For instance, instead of writing:
<script type="text/javascript" language="javascript" src="script.js"></script>
We write:
<script src="script.js"></script>
Conclusion
We should keep up with new constructs.
They probably save us time.
Other goodies including self calling functions, simplifying script tags, and many things in the JavaScript standard library.