Overview
What do you think about when you think about code quality?
Is it consistency? Enforcing a set of standards and best
practices on your code through linter rules and formatters?
How about ensuring your code has tests that run
automatically during your build process? What about pull
requests and code reviews — protecting your master branch
from direct commits and having peers review your code?
They’re some of the things that come to mind for me. I can
write code that passes all the automated processes without
any guarantee to its actual quality. When the mess in your
code increases, so does the time that it takes to maintain it.
However we all forget the human factor who are involved in
writing those codes.
To prevent this situation you should take care of the quality
of the code. You should invest time in the quality of your
code. Here’s a list of eight things that can be done to
improve code quality. Some of these things can be done as
an individual, others are more of a team effort.
1) Meaningful Variable/Function Names
First and foremost code quality attribute is variable/function
names. It is fine to use const a = “value” when you are
learning JS. But using such practices would pain for you and
other fellow developers when you will be working on any
project. Let’s say you have written the following code.
When you write this code, you would know what this variable
is used for. Will you be able to understand what these
constants mean and where they are used? Maybe 🤔 . Because
you have written that. What about your fellow coder, would
he/she be able to understand it? I hope you got the problem I
am talking about. Contrary to the code above, we have a
better one below.
This way your code is readable and understandable for a
person who is seeing it for first time also it would be much
easy to troubleshoot an issue for you. Same goes for function
names too.
2) Block Scoped Declarations
Since the inception of the language, JavaScript developers
have used var to declare variables. The keyword var has its
quirks, the most problematic of those being the scope of the
variables created by using it.
var x = 10
if (true) {
var x = 15 // inner declaration overrides declaration in parent scope
console.log(x) // prints 15
}
console.log(x) // prints 15
Since variables defined with var are not block-scoped,
redefining them in a narrower scope affects the value of the
outer scope.
Now we have two new keywords that replace var,
namely let and const that do not suffer from this drawback.
let y = 10
if (true) {
let y = 15 // inner declaration is scoped within the if block
console.log(y) // prints 15
}
console.log(y) // prints 10
const and let differ in the semantics that variables declared
with const cannot be reassigned in their scope. This does not
mean they are immutable, only that their references cannot
be changed.
const x = []x.push('Hello', 'World!')
x // ["Hello", "World!"]x = [] // TypeError: Attempted to assign to readonly
property.
3) Using Array Prototype methods instead of
looping
All JavaScript objects inherit properties and methods from a
prototype. We all would have written loops in our code for
various things to solve.
let fruits = ['Banana', 'Apple', 'Orange', 'Mango'];for(var i = 0; i < fruits.length;
i++) {
console.log(fruits[i]); // To print fruits array
}
4) Remove unused JavaScript code
If there is any unused methods, variables, loops or
conditional statements in the code, identify those and
remove. This would help during build in reducing the overall
size of the app and improve the download time. Also, the
browser will take less time to analyze the code.
5) Minify Your JavaScript Code
This is sort of a continuation of the previous tip. While I
advised you to get rid of unused code, this one tells you to
get rid of useless non-code stuff inside your JS files. What
does that mean? A typical source code file — not only in
JavaScript but also in any language — contains things that
are meaningful to developers but quite useless to the
machine. Examples include the following:
Comments
White lines
White spaces
Indentation
The items above are necessary in order to make code easier
to read and navigate, but when it comes to the interpretation
or compilation of the code, they’re just useless bytes.
6) Default values using || operator
In JS there is a basic rule of having a default value otherwise
process will halt at undefined values.
To provide default value in a variable use || to stay away from
this most common issue.
var a = a || 'hello'
The developer must check whether there are any conflicting
values that might be passed to the function to avoid Bugs.
7) Replacing JavaScript switch/if…else
statement with object literals
Complex conditions in JS have always been a source of
redundant code. However, using object literals in JavaScript
can save you this problem. An object literal in JavaScript is a
comma-separated list of key-value pairs wrapped in curly
braces.
function getEmoji(mood) {
switch(mood){
case 'happy':
return '😊';
case 'sad':
return '😔';
case 'angry':
return '😡';
default :
return '😑';
}
}
function getEmoji(mood) {
if(mood === "happy") {
return '😃';
} else if (mood === "sad") {
return '😔';
} else if (mood === "angry") {
return '😡';
} else {
return '😑';
}
}
The above switch or if..else statement can be reduced to
object literals like below.
function getEmoji(mood) {
let emoji= {
'happy': '😊',
'sad': '😔',
'angry': '😡',
}[mood];
return emoji || '😑';
}
Why to do this?
Easily understandable
No need for a break statement
Minimal code
Can add new cases in object easily
These are some of the tricks to improve your code quality in
javascript to begin with. There are lots of other ways to
improve.
Happy Coding