How These 6 Tips in Javascript Will Help You In Writing A Cleaner Code

Good and clean code -> lower maintenance cost

Stefen Suhat
Xendit Engineering
7 min readMar 19, 2021

--

As we know Javascript is one of the most used primary languages in the world of programming. Javascript popularity keeps increasing, not only for the web but now it can be used to build hybrid mobile apps, i.e: React Native.

One of the most famous Javascript libraries for building UI is React JS. React JS created by Facebook to build painless interactive UIs. Just by designing simple views for each state in your application, React will efficiently update and render just the right components when your data changes.

In this blog, we’ll take a look at how we have some tips and tricks when building a web / mobile app using Javascript & React:

1. Use Identity Operator (===) instead of Equality Operator (==)

As a developer we tend to make mistakes when comparing between values especially if the data coming from the 3rd party API, or sending data to API that makes the API returns client-side errors. Because some of developers tend to use equality operators instead of identity operators.

The main difference is Equality Operator will ignore the data type and instead, only compare the value. To make it easier let’s look at an example:

As we can see, lines 2 and 4 are where the difference is. If we are using == to compare, it will ignore the data type of “1” as a string and only look at 1 as its value. It will only compare its value. However, with === line 4 is will return false because of different data type 1 (number) compare with 1 (string).

2. Replacing For-Loop statement using Map or forEach

Before es6 map and forEach is announced we always do looping using for-loop — which is slow especially on large data and make code become so difficult to read when you have a long function on each iteration.

For making a cleaner code and increasing maintainability we start moving from for-loop statement to map-foreach statement.

As we can see map and forEach has shorter code and more readable code. When using map-foreach you can directly get objects from every iteration. p.id instead of For you need to specify posts[i]['id'] .

Performance

Benchmark

Benchmark results:
foreach x 11,313 ops/sec ±7.16% (55 runs sampled)
for x 6,018 ops/sec ±7.15% (34 runs sampled)
map x 10,514 ops/sec ±6.86% (56 runs sampled)

For performance-wise, map and forEach don’t really have some differences. But start showing big differences when using for statement.

The main difference between Map and forEach is that Map returns an array. So what’s the purpose of forEach? You can use forEach as an iteration array and sum a few numbers together or save data to the database.

But of course, the above example can be done using map function. Most of the time we don’t use forEach because the same thing can be achieved with Map.

3. Replacing var with const and let

Since ES6 is announced, we start moving from var to const and let for variable declaration. The problem within var is scope declaration.

Since number === 2 is return true than text will get replaced. The problem with this is if you know the text variable is declared and you are trying to re-defined it but it will become a problem if you didn’t know the text variable is already defined before. Because maybe some part of your code before is using text variable, but because of the if statement changes the value your whole app will act differently from what you expect.

Here comes the saver, let and const.

Let

Within the scope Let can be updated if you want to change the value. But it will return an error if you are trying to re-declared the variable.

Const

The main difference between const and let are const cannot be updated or re-declared.

You can take const as a final variable.

4. Use functional component instead of class component for ReactJS

Sometimes when building a React web/app we faced multiple unnecessary re-render, or code become harder to debug as it becomes bigger. If you are facing this maybe it’s time to migrating to the functional component.

Basically, all functional components can do, a class component can also do it.

The main different class components need to extend React. Component. With functional components you are writing less code and cleaner code — but again it depends on how the developer is writing the code and how they can manage the code consistency.

Wait. Doesn’t the functional component cannot access the state? Yes, previously before React 16.8 functional component cannot access the DOM directly — state. But since React 16.8, React announce a new useState method which makes functional components become stateful. Furthermore, with the introduction of React.memo higher-order component we can use memoization to avoid re-rendering of a functional component given that it renders the same stuff for the same props (shallow tested for difference).

Class Component
Functional Component

5. Use code-splitting for smaller size script and better performance

Most React apps will have their files “bundled” using tools like Webpack, Rollup, or Browserify. Bundling is the process of following imported files and merging them into a single file: a “bundle”. This bundle can then be included on a webpage to load an entire app at once.

Bundling is great when your app is small and not including too many 3rd party libraries. Because bundling it into 1 file makes the file size tend to become bigger. So, you need to get extra cautious when extending it.

But our app is getting bigger and bigger. That’s the time we use the code-splitting tool. To avoid a large bundle of a single file, it’s time to start “splitting” your bundle. Code-Splitting is a feature supported by bundlers like Webpack, Rollup, and Browserify (via factor-bundle) which can create multiple bundles that can be dynamically loaded at runtime.

Code-splitting your app can help you reduce your file size into a smaller chunk, which can dramatically improve the performance of your app. While you haven’t reduced the overall amount of code. Then how it works? It “lazy-load” your unused code, so it will reduce the amount of code needed during the initial load.

This will automatically load the bundle containing the FooBar when this component is first rendered. In the meantime, HelloWorld component will still be loaded as a single bundle file.

React.lazy takes a function that must call a dynamic import(). This must return a Promise which resolves to a module with a default export containing a React component.

The lazy component should then be rendered inside a Suspense component, which allows the component to show some fallback content (such as a loading indicator) while it waiting for the lazy component to load.

At Xendit we use code splitting by default. Because it reducing the load time of the script especially on the first load. Our pages won’t be loaded unless the user needs them. So it makes the web become faster and can interact quicker. The lazy load will avoid unnecessary resource downloads or code execution. However, it can’t help with a single bundle file.

6. Use ESLint to make code more cleaner and structural across the team.

When working as a team with unique individuals and code styles, it’s hard to maintain how the code looks like. Some programmers are like to use camelCase word, some like using snack_case word. Without consistency on the large app will take a significant amount of time to debug and error-prone.

As you can see the difference in lines 4 and 9. Line 4 uses 2 spaces, and line 9 use 4 spaces. The difference is quite small, but try to think if it’s a big large project and you have long line code. It will be confusing when you debugging because of the difference in indenting.

Solution: Linter. Linter not only taking care of your code consistency. Linters are also great tools to find certain bugs, such as variable scope, assignment to undeclared variables, etc.

ESLint is one of the most popular Javascript linter.

ESLint statically analyzes your code to quickly find problems. ESLint is built into most text editors and you can run ESLint as part of your continuous integration pipeline.

You can easily install ESLint using npm install --save-dev eslint or yarn add eslint --dev and add eslint.rc to your project codebase

You can search so many plugins for ESLint setup. A plugin can help you, so you won’t need to set the rules 1 by 1. If you are starting React project with create-react-app the project by default will include ESLint setup with react-app plugin. You can learn more here.

There are some few most popular plugin for ESLint as well such as eslint-config-airbnblink.

Try to find what are you and your team most suitable using. Add some new rules or remove them if you think it’s unnecessary.

That’s some few small tips and trick to make your code less prone to error, easier to read and make your code cleaner.

That just a small factor of having a clean and easier code to write. It’s not always easy to learn something new. Enjoy the process, and you will fall in love with it.

Thanks for reading!

--

--