11 Simple Tips For Writing Better JavaScript Component Code

Newbie coders rarely take the road less travelled. The destination is reached, but the journey forward is necessarily fatiguing. Sounds unfamiliar? Hang on. Often, what you have with beginners is quickly produced working code, but not quality code. Instead of terse, flexible components, you have clunky blocks that make for very little scalability. Amateurs tend to have a ‘this is temporary, we’ll fix it later’ kind of attitude, which does not hold well in the higher realms of coding where, to quote Robert C. Martin, clean code reads like well-written prose’.

However, delivering efficient components on deadline is as difficult as writing poetry on demand. You want your component to be as reusable as a Lego block, as shareable as a secret, as light as a feather, and as simple as simple can get. But what you land up with is a component that is born lean and grows clunky – with several ‘bug-fixes’ tacked onto it at every end – and lands up being unusable in just a short while. To avoid such a scenario, which can be costly in many senses, it is a smart idea to backtrack a bit and line up your tactics against best practices that experienced coders abide by.

Here are 11 tips for writing better JavaScript components you can implement going forward.

1. Keep it short and simple (KISS)

When Eric Elliot publicly took to Twitter to get views on ‘what people think the biggest/most common mistake software developers make is?’, Brendan Eich, co-founder of the Mozilla Foundation, favorited 2 views: “not being pragmatic, overcomplicating things” and “underestimating their talent”.

The KISS principle is a good antidote to over complication as it pertains both to brevity (short) and logic (simple). In practical terms, once you have got your first draft down, start asking questions like:

  • The code works, but can it be more concise?
  • Can I use functional components to better the logic?
  • What can I define externally?

With an eye on optimization, you will soon be writing code that’s performant and light.

2. Make use of destructuring

The destructuring syntax is great for making your code shorter, and more readable too. It works with arrays and objects, allowing you to unpack values and properties and bind them to variables. And what is even better is that you can extract a whole bunch of variables with a single statement, which means that it is a very practical way of making complex functions uncomplicated. You can use the destructuring syntax with nested arrays/ objects as well.

3. Avoid functions with side effects.

Pure functions give you the same output if given the same input, always. They have zero side effects (mutations). To take your functional programming game up a notch, make it a practice to always use pure functions when you can. It’ll help you create components that are scalable and reusable, yes, but also free from bugs crawling about a shared mutable (e)state.

4. Do not repeat yourself.

Stick to the DRY principle, as coined by Andy Hunt and Dave Thomas in The Pragmatic Programmer. It’ll help keep your codebase cleaner and your components reusable. Maintainability, testing, and costs are also at stake here and having unnecessary code scattered about the place makes it that much harder to keep your software free of bugs. To start ‘DRYing’ up your code, look for patterns and repetition and then, replace that with abstractions. Rinse, repeat, DRY.

5. Prefer functional components.

If you are ever at the ‘functional vs class’-component crossroad, stop. Can a functional component do the job? If yes, use one. Functional components are plain, old, ‘dumb’, clean, and simple. No boilerplate, no lifecycles, no states—just less code and chock full of JavaScript best practices. What is there to not love about them?

6. Limit lines, characters, and indentation

Extremely long code does not necessarily display erudite coding skills. In fact, it is better to write in smaller chunks, so that you (or someone else!) can go back to your code in search for a nugget of logic anytime later and not be lost searching for a needle in a haystack. Some believe 500 lines is a limit you should not trespass. Others would say less. But the idea is that you keep your components maintainable. The same goes for:

  • Indentation: 4 to 5 levels seem like a limit to keep to
  • Characters: The 80-character limit allows you to line up two tabs side-by-side with ease

7. Name variables and components smartly

You want to go about naming based on content and not context, because you want your code to be easily used in other contexts too. In terms of functions, think about what job it is doing. Next, a good practice is to start with a verb, because a verb is how you get a job done. So, generate Playlist is a good name. For components, it is better to be more generic. Playlist would be better than Audio Playlist or Video Playlist, which could make the component seem restricted in its functionality.

8. Learn when to use async/ await.

You will find a ton of guides online advocating the use of async-await, but before you sync with the trend, wait a bit, and think if over-generalization makes for any good in the long run. Rather than be polarized, look at async-await and promises as tools you can use to make your code more potent. And the only question is which one to use. On Medium you can find quite a comprehensive set of rules, which are worth checking out.

9. Aim for one component, one function.

In the world of components, small and function-specific is reusable. Also, if your component is working with generality, you have a better chance of sharing it with other teams. And smaller components are easier to test and maintain too. Large components can work, but you would probably be trading off reusability, testability, shareability and the joy of having less code!

10. Skip commenting and code more clearly.

Some coders believe that including a lot of comments is like the old saying, “empty vessels make the most noise”. See this quote from an article on Towards Data Science:
“In general, comments are a wart that stipulates poor design, especially long-winded comments where it’s clear the developer didn’t have a clue what the heck they are doing and tried to make up for it by writing a comment.” – Sabesan Sathananthan
But CodeinWP is a bit more technical with their evaluation. They say commenting can:

  • Increase clutter, visually.
  • Cause a conflict between code and comment to arise.

11. Try vanilla JavaScript!

It is good to make your favorite coding flavor vanilla, because frameworks can come and go (and indeed they do) but understanding the language behind the libraries is bound to pay richer dividends. Vanilla JavaScript is powerful, and in case you are building components for multiple UI frameworks and libraries, going framework-agnostic, at least to a level, may be the best and only way for you to keep your code maintainable and free from duplication. 
To these 11 best practices, you can add several others like:

  • Organize all component-related files.
  • Use props carefully.
  • Test your code to ensure zero crashes.

But to really grow as a JavaScript software engineer, it’s necessary to get hands on real-world experience, and rub shoulders with professionals who know of a ton of more tips and nuances, all learnt by way of experience.

— 0o0 —

As one of leading software development outsourcing companies in Vietnam, Titan Technology always use cutting-edge technologies to deliver all the best outcomes to our partners in over the world along with providing above good environments for any developer will need to explore themselves in this market.

In case you just grew your interest in working with Titan Technology, we are opening for many positions that suit with all your potential.
For your own feeling about Titan, feel free to check our website and submit your CV to us if you already have interest to become a Titaner :

Source: By HarVar