After years of writing JavaScript code, could your code be more elegant? Here are some suggestions for optimizing the code. We can refer to them and hope to give you some help.

1. The congruent and incongruent operators are recommended

ECMAScript provides two sets of operators: equal and unequal (== and! =) — convert before comparing, congruent and incongruent (=== and! ==) — only compare, not convert

The congruent and incongruent operators are no different from the equality and inequality operators, except that the operands are not converted before comparison

As follows:

var result1 = ("66"= = 66); //trueVar result2 = ("66"= = = 66); //falseBecause different data types are not equalCopy the code

Remember: null == undefined returns true because they are similar values; But null === undefined returns false because they are different types of values.

Due to type conversion problems with equality and inequality operators, it is recommended to use congruence and incongruence operators in order to preserve the integrity of data types in your code. If the type of the variable is already determined, then using == is not necessary at all; If the type is uncertain, the conversion should be done manually:

var code = "5";
if(parseInt(code) === 0){

}
Copy the code

2. You are not advised to change the type of the value stored in the variable

Variables are loosely typed, meaning they can be used to hold any type of data. In other words, each variable is just a placeholder to hold a value; The following code:

var message = "hi"; 
Copy the code

Initializing a variable like this does not mark it as a string; The initialization process is as simple as assigning a value to a variable. Therefore, it is possible to change the type of the value as well as the value of the variable:

var message = "hi"; message = 100; // Valid, but not recommendedCopy the code

This gives the impression that it is too arbitrary and unreadable, and at the same time, the JS engine takes extra time to compile, which is bad for performance. The recommended way to initialize a variable is to give it a default value:

var message = "hi",
    found = false,     
    age = 29
Copy the code

3. Avoid extending the scope chain

Extension of the scope chain occurs in two cases:

  • The catch block of a try-catch statement;
  • With statement

Both statements add a variable object to the front of the scope chain. For the with statement, the specified object is added to the scope chain. For catch statements, a new variable object is created that contains the declaration of the error object that was thrown.

As we know, identifier resolution is the process of searching identifiers level by level along the scope chain. The search process always starts at the front of the scope chain and works backwards until the identifier is found, so the longer the scope chain, the slower the search.

4. Cache variables

For example, array length:

 for (let j = 0; j < area.geo.length; j++) {
     
 }
Copy the code

You should write to a variable to avoid looking up the object and calculating the length every time you loop

let geoLength = area.geo.length
for (let j = 0; j < geoLength; j++) {
     
 }
Copy the code

In addition, cache variables can be dom optimized:

let odiv=document.getElementById('content'); // Next is some code to manipulate the DOM...Copy the code

This avoids multiple attempts to find DOM elements, which can improve code efficiency.

5. About the if statement

One of the most common statements in most programming languages is the if statement. Here are three suggestions:

(1) Always use code blocks

A good practice in the industry is to always use blocks of code, even if there is only one line of code to execute. This eliminates misunderstandings that might otherwise confuse people about which statements to execute under different conditions.

if (i > 25)    
alert("Greater than 25."); // Single line statementelse {     
alert("Less than or equal to 25."); // Statements in code block}Copy the code

(2) Replace the simple if-else with the trinary operator

For example, a simple function:

lightBackground () {
      if(this.mode === 'dark') {return normal
      }else {
           return light
      }
    }
Copy the code

Using the ternary operator makes writing less bloated and more clear

 lightBackground () {
      return this.mode === 'dark' ? 'normal' : 'light'
    }
Copy the code

The original five lines of code now need only one line, and the code is more efficient than before.

(3) Optimize nested conditional statements

For example, there are a lot of if-else statements:

if (index === 0) {
       fn0();
      } else if (index === 1) {
        fn1();
      } else if (index === 2) {
        fn2();
      } else if (index === 3) {
        fn3();
      }
Copy the code

You can optimize your code with switch statements. Basically, switch statements are designed to keep developers from writing code like the one above.

switch(index){
    case 0:
    fn0();
    break;
    case 1:
    fn(1);
    break;
    case 2:
    fn2();
    break;
    case 3:
    fn3();
    break;
    default:
    fn()
}
Copy the code

Or use object methods instead:

let idxObj = {
    0: fn0,
    1: fn1,
    2: fn2,
    3: fn3,
    4: fn
}
if(num in idxObj){
    idxObj[num]()
}
Copy the code

6. Use short circuit operators wisely

The operations of logic or and logic and are short-circuited, that is, if the first operand determines the result, the second operand is not evaluated.

(1) We can use the behavior of logic or to avoid assigning null or undefined values to variables.

Such as:

const hmsr = this.$route.query.hmsr || query.hmsr || ' '
Copy the code

This pattern is often used in assignment statements of ECMAScript programs.

(2) logic and can avoid calling undefined attribute error

watch: {
    carList (to) {
      this.swiper && this.swiper.slideTo(0)
    },
  },
Copy the code

7. Optimization of functions

In JavaScript development, most of the time can not do without functions, about functions, here are some suggestions:

(1) The naming of functions

Function names should start with a verb, such as getName(). Functions that return Boolean values generally start with is, such as isEnable().

(2) Specify the return type of the function

For example:

function getPrice(num){
    if(num < 0) return "";
    else return num * 20;
}
Copy the code

This function sometimes returns an empty string, and sometimes an integer. Writing this way will not report errors, but may be behind the code buried hidden trouble. And if you do it by accident, you get NaN, O (╯□╰) O. The recommended way to write it is:

function getPrice(num){
    if(num < 0) return- 1;else return num * 20;
}
Copy the code

This avoids unnecessary errors and makes the function clearer and less confusing.

(3) Parameters of the function

In practice, passing parameters to a function is unavoidable, but if a function is passing a long list of parameters, it can seem very scary, and the person using the function must not only understand the meaning of each parameter, but also make no mistakes.

So we should reduce the parameters of the function as much as possible, we can put the parameters into an object, and then pass the object to the function

8. Some use of ES6

The use of ES6 in your code can make your code much cleaner, and of course there are many. Here are a few commonly used ones:

(1) Backquotes (‘)

Template strings are enhanced strings, identified by backquotes (‘). It can be used as a regular string, it can be used to define multi-line strings, or it can be used to embed variables in strings.

In traditional JavaScript languages, the output template would look like this:

	citys="<li value="+item.xzqh+">"+item.name+"</li>";  
Copy the code

A variable is embedded in the template string. You need to write the variable name in ${}.

citys=`<li value="${xzqh}">${name}</li>`; 
Copy the code

Using template strings to represent multi-line strings, all whitespace and indentation are preserved in the output.

$('#list').html(`
<ul>
  <li>first</li>
  <li>second</li>
</ul>
`);
Copy the code

In the above code, all template string whitespace and line breaks are reserved, such as a line break before ul tags.

(2) Arrow function

The arrow function makes the presentation more concise.

const isEven = n => n % 2 === 0;
const square = n => n * n;
Copy the code

The above code defines two simple utility functions in just two lines. If you didn’t use the arrow function, it would take up multiple lines, and it wouldn’t be as bold as it is now.

One use of the arrow function is to simplify the callback function.

[1,2,3].map()function (x) {
  returnx * x; }); [1,2,3]. Map (x => x * x);Copy the code

Java uses the -> arrow, C# uses the same arrow as JS: =>, which is called the “lambda operator”.

Lambda expressions (arrow functions) are said to be the simplest way to define functions, with almost no redundancy left in the syntax. Because of the weak typing nature of JS, lambda expressions in JS are much more concise than in C# and Java.

(3) Use ES6 class

Although the ES6 class and function prototype are no different in principle, they are both used in the prototype. Classes can be inherited through the extends keyword, which is much cleaner and more convenient than by modifying the stereotype chain.

Such as:

function Person(name, age){
    this.name = name;
    this.age = age;
}

Person.prototype.addAge = function(){
    this.age++;
};

Person.prototype.setName = function(name){
    this.name = name;
};
Copy the code

Using class, the code looks clean and easy to understand

class Person{
    constructor(name, age){
        this.name = name;
        this.age = age;
    }
    addAge(){
        this.age++;
    }
    setName(name){ this.name = name; }}Copy the code

conclusion

These are some tips for making your code look elegant, but not just elegant. Sometimes one or two lines of code you write can make a big or small difference in performance. More concise and efficient code is not only a reflection of your ability, but your team needs to write elegant and efficient code to improve the overall efficiency of the team.

Pay attention to our