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.
No Ternary Expressions When Simpler Alternatives Exist
We shouldn’t write ternary expressions when simpler alternatives exist.
For instance, if we have:
let score = val ? val : 0
Then we should write:
let score = val || 0
instead, since they do the same thing.
If val
is falsy, then 0 will be returned in both examples.
No Unreachable Code After return, throw, continue, or break Statements
If we write those statements, then we should make sure that the code that comes after it is still reachable in some cases.
For instance, we shouldn’t have code like:
function foo () {
return true;
console.log('never');
}
The console log isn’t reachable since it comes after a return
statement that always runs.
No Flow Control Statements in finally Blocks
We shouldn’t have flow control statements in finally
blocks.
JavaScript suspends flow control statements of try
and catch
blocks until the execution of the finally
block finishes.
So when return
, throw
, break
, or continue
are used in finally
, the control flow statements in try
or catch
are overwritten.
Therefore, unexpected behavior may result.
So we shouldn’t write code like:
try {
// ...
} catch (e) {
// ...
} finally {
return 1;
}
The Left Operand of Relational Operators Shouldn’t be Negated
If we have code like:
if (!key in obj) {}
Then only key
is negated, which is probably a mistake.
Instead, we should negate the whole expression:
if (!(key in obj)) {}
Avoid Unnecessary Use of call and apply
We only need to use call
and apply
to change the value of this
inside a function.
Other than that, we can use the spread operator to spread array entries into arguments instead of calling apply
.
So instead of writing:
sum.call(null, 1, 2, 3)
We write:
sum.call(1, 2, 3)
or:
sum.call(...nums)
Don’t Use Unnecessary Computed Property Keys on Objects
We shouldn’t use unnecessary computed property keys on objects.
They are useless and can be simplified.
For instance, instead of writing:
const user = { ['name']: 'james' };
We write:
const user = { name: 'james' };
No Unnecessary Constructor
If we have an empty constructor in our class, then we don’t need it.
So we shouldn’t write:
class Car {
constructor () {
}
}
as JavaScript will provide an empty constructor for us.
No Unnecessary Use of Escape Characters
We shouldn’t escape characters in a useless way.
Therefore, we shouldn’t write code like:
let message = 'hello'
Don’t Rename Import, Export, and Destructured Assignments to the Same Name
There’s no point in renaming imports, exports, and restructured assignments to the same name.
Therefore, we shouldn’t do this.
For instance, instead of writing:
import { foo as foo } from './config'
Instead, we just write:
import { foo } from './config'
No Whitespace Before Properties
Whitespace before properties are useless and don’t follow commonly accept JavaScript code formatting conventions.
Therefore, we shouldn’t have them.
For instance, instead of writing:
user .password
We write:
user.password
No with Statements
We should never use with
statements.
They are disallowed in strict mode.
Also, they create variables with confusing scopes.
Therefore, we should never write things like:
with (obj) {...}
Have Consistency in Newline Between Object Properties
When we defimen object literals, we should either have newlines after each property.
Or we can puyt all the properties of the same line if they won’t overflow the page.
For instance, we either write:
const user = { name: 'jame', age: 30, password: '123' }
Or we write:
const user = {
name: 'jame',
age: 30,
password: '123'
}
No Padding within Blocks
We shouldn’t have padding within blocks.
For instance, we shouldn’t write:
if (user) {
const name = getName()
}
Instead, we write:
if (user) {
const name = getName()
}
Conclusion
We shouldn’t have useless whitespaces.
Also, we should format object consistency when it comes to newlines.
We also should make sure that we don’t have any unreachable code in our blocks.