JavaScript refactoring tips-make functions simple and clear

Posted May 28, 20204 min read

John Au-Yeung

Like it and see it again, develop a habit

This article GitHub has been included, more classification of previous high praise articles, also sorted out A lot of my documents, and tutorial materials. Welcome Star and Perfect, everyone can refer to the test site for review in the interview, I hope we have something together.

JavaScript is an easy-to-learn programming language, and it is easy to write programs that run and perform certain operations. However, it is difficult to write a clean JavaScript code.

In this article, we will study how to make our function more clear.

Use destructuring on object parameters

If we want the function to accept many parameters, then objects should be used. On this basis, we can use the destructuring syntax to extract the parameters we need.

For example, for object parameters, we might use it like this:

const greet =(obj) => {
  return `${obj.greeting}, ${obj.firstName} ${obj.lastName}`;

The above syntax, we can use the deconstruction method will be more elegant:

const greet =({
}) => {
  return `${greeting}, ${firstName} ${lastName}`;

In this way, we can write less repeated things, and the naming will be more clear.

Named callback function

Good naming will make it easier to read the code, and the naming of the callback function is the same, for example, the following bad naming method:

const arr = [1, 2, 3].map(a => a * 2);

We can name them separately like this:

const double = a => a * 2;
const arr = [1, 2, 3].map(double);

Now we know that our callback function is actually used to double each element of the original array.

Make the conditional sentence descriptive

By writing a conditional expression in the conditional statement of your own function, you can make the conditional statement more descriptive.

For complex conditional judgments, we can use functions alone to express conditional statements, such as the following code:

if(score === 100 ||
  remainingPlayers === 1 ||
  remainingPlayers === 0) {

When there are many conditions, we can use functions to express:

const winnerExists =() => {
  return score === 100 ||
    remainingPlayers === 1 ||
    remainingPlayers === 0
if(winnerExists()) {

In this way, we know that these conditions are conditions to check whether there is a winner in the game code.

In the first example, we have a very long expression in parentheses, most people may not know what it is judging. But in the second example, once we put it in a named function, we know what it is probably judging.

Having a named function in a conditional statement is much clearer than having a bunch of boolean expressions.

Replace switch statement with Map or Object

Because the switch statement is very long, this is error-prone. Therefore, if possible, we should replace them with shorter codes. Many switch statements can be replaced with map or object. For example, if we have the following switch statement:

const getValue =(prop) => {
  switch(prop) {
    case 'a':{
      return 1;
    case 'b':{
      return 2;
    case 'c':{
      return 3;
const val = getValue('a');

We can replace it with object or map as follows:

const obj = {
const val = obj ['a'];

As we have seen, the switch syntax is very long. We need to nest multiple blocks with multiple return statements just to get the return value given the prop value.

Instead of using objects, we only need one object:

const obj = {

Another advantage of using objects is that they do not have to be valid identification symbols for keys, which adds more flexibility.

We can also use map to replace objects as follows:

const map = new Map([['a', 1], ['b', 2], ['c', 3]])
const val = map.get('a')

As we can see, when using Map, the code is also much shorter. We pass an array, each item in the array contains keys and values. Then, we only use the get method of the Map instance to get the value from the key.

One advantage of Map over objects is that we can use numbers, booleans or other values such as objects as keys. Objects can only use strings or symbols as keys.

to sum up

Using destructuring syntax can make object parameters clearer and shorter. In this way, you can selectively access attributes as variables.

By placing the conditional expression in its own named function, you can make the conditional expression more descriptive. Similarly, we should name the callback function to make it easier to read the code.

Finally, you should replace switch statements with Map and Object whenever possible.

Bugs that may exist after the code is deployed cannot be known in real time. In order to solve these bugs afterwards, a lot of time is spent on log debugging. By the way, I recommend a useful BUG monitoring tool Fundebug .

Original: https://levelup.gitconnected ....

communicate with

The article is continuously updated every week, you can read WeChat search "Great Move World" for the first time to read and reminder(one or two earlier than the blog), this article GitHub has been included, a lot of my documents have been compiled, welcome Star and perfect, everyone can refer to the test site for review during the interview, and pay attention to the public number, reply welfare in the background, you can see the benefits ,You know.