What’s the most important thing to focus on when writing code

There are a few rules to writing code, to think about style and efficiency, to think about conventions if the team is writing together, and finally to think about our usage scenarios and how we should design them.

style

In the team, everyone may have different styles. Some people like to use semicolon at the end, some people do not use semicolon, and there are indentation problems. Some people like to use space, some people like to use TAB, TAB indentation also has 4 characters and 2 characters.

There is no such thing as a good or bad style, but there should be consistency in a team, and we can use ESLint to unify style constraints.

The efficiency of

Sometimes when we write code, readability and efficiency are not the same, depending on our business scenario. There is no good or bad in this, it is only a matter of choice.

Left – pad

There was a huge incident on GitHub when the developers of Left-pad withdrew their open-source code. The NPM package was used by many large projects at the time. The left-pad has only eleven lines of code

module.exports = leftpad;
function leftpad (str, len, ch) {
  str = String(str);
  var i = -1;
  if(! ch && ch ! = =0) ch = ' ';
  len = len - str.length;
  while (++i < len) {
    str = ch + str;
  }
  return str;
}
Copy the code

1. Granularity of the NPM module

We see the above module, just 11 lines of code, but so many people are using it that it’s hard to understand why so many people are using it today. At that time, packaging tools were not very flexible. For example, several apis were introduced into the module. We only wanted to use these apis.

2. Code style

In fact, the style of this code is very readable, and the efficiency of the ALGORITHM of ON is also quite good. We can also improve the space, which can make the code more brief and efficient.

3. Code quality/efficiency

/ / leftpad optimization
    function leftpad(str,len,ch = ' '){
        str = "" + str;
        const padlen = len - str.length;
        if(padlen <= 0) {return str;
        }else{
            return (""+ ch).repeat(padlen) + str; }}console.log(leftpad(1.8));
Copy the code

There is also an example in MDN developer.mozilla.org/en-US/docs/…

Finally, we can use this method for optimization.

 var rpt = " ";
 do {
 rpt += srt;
 str += str;
 count &= count -1;
 } while(count);
Copy the code

Usually we don’t use this very often, so there’s no need to over-optimize. Finally, back to the top, we must set up our code according to the scenario.