1. Use numeric delimiters

This is one of the most commonly used operators when dealing with large numbers. When you use delimiters (that is, _) in numbers, they look nicer than undelimited numbers.

Before use:

let number = 98234567;
Copy the code

After use:

let number = 98_234_567;
Copy the code

And this technique can be applied to other base values as well:

const binary = 0b1000_0101;
const hex = 0x12_34_56_78;
Copy the code

Matters needing attention:

You can’t use it after the first 0.

let num= 0_12; / / errorCopy the code

Do not appear at the end of a number.

let num= 500_;
Copy the code

Always use a semicolon

Using a semicolon as a line termination is a good practice. If you forget to write, you won’t be warned because JavaScript parsers insert semicolons in most cases, but you shouldn’t rely on Automatic Semicolon Insertion.

Google, Airbnb, and jQuery also include this in their JavaScript style guides.

Don’t forget var

When you first assign a value to a variable, make sure you are not assigning to an undeclared variable.

Assigning a value to an undeclared variable causes global variables to be created automatically. Be careful not to use global variables lightly!

Global variables can easily be overwritten by other scripts. For example, if two separate parts of your application define global variables with the same name but different uses, that can lead to unpredictable errors, and you don’t want to go through the pain of debugging such problems.

Therefore, it is best to limit the scope of your code so that global scope is used as little as possible. The more global variables you use in a script, the more difficult it is to interact with another script.

In general, variables in a function should be local so that when you exit the function they can leave with success.

4. delete vs splice

Delete items from an array by using splice instead of delete. Using DELETE deletes object properties, but does not reindex the array or update its length. This makes it look undefined.

Delete

> myArray = ['a', 'b', 'c', 'd']
  ["a", "b", "c", "d"]
> delete myArray[0]
  true
> myArray[0]
  undefined
Copy the code

Notice that it is not actually set to undefined, but rather removes the attribute from the array to make it look like undefined. Chrome development tools make this distinction clear by printing blank space when recording arrays.

Splice

Splice() actually deletes elements, reindexes the array, and changes the array length.

> myArray = ['a', 'b', 'c', 'd']
  ["a", "b", "c", "d"]
> myArray.splice(0, 2)
  ["a", "b"]
> myArray
  ["c", "d"]
Copy the code

The delete method should be used to delete object properties.

5. Map vs for loop

Use the map() function method to loop through the items of the array.

Var squares = [1,2,3,4]. }); // squares will be equal to [1, 4, 9, 16]Copy the code

Immutability – The original array is not affected. Just in case the original array is still needed somewhere else. You could also write a for loop to not update the original array, but that would require more code and update the new array as part of the loop operation. Map (), on the other hand, is cleaner because you only need to work in one scope.

Cleaner code – When doing the same thing, you can almost always write less code with map than for: sometimes even one line of code, which requires at least two, and usually three, lines of code and curly braces. In addition, scoped isolation and a reduction in the number of variables required make the code objectively cleaner.

6. Round

The toFixed() method converts the rounded number to the specified decimal number.

Var PI = 3.1415; pi = pi.toFixed(2); // PI will be equal to 3.14Copy the code

Note: toFixed() returns a string, not a number.

7. Use the console. The table

You can use console.table to display objects in tabular format:

table=[{state: "Texas"},{state: "New York"},{state: "Chicago"}]
console.table(table)
Copy the code

8. Avoid try-catches in loops

Each time a catch clause is executed, the try-catch structure creates a new variable at run time for the current scope, to which the caught exception object will be assigned.

Use try-catch in loops:

var object = ['foo', 'bar'], i;  
for (i = 0, len = object.length; i <len; i++) {  
    try {  
        // do something that throws an exception 
    }  
    catch (e) {   
        // handle exception  
    } 
}
Copy the code

After the improvement:

var object = ['foo', 'bar'], i;  
try { 
    for (i = 0, len = object.length; i <len; i++) {  
        // do something that throws an exception 
    } 
} 
catch (e) {   
    // handle exception  
}
Copy the code

When an error occurs, the first piece of code continues the loop and the second piece exits. If the code does not throw an exception that is serious enough to stop the entire program, the first piece of code is better.

9. Multiple condition checks

For multi-value matching, we can put all values in an array and use indexOf() or includes() methods.

Here’s the code

if (value === 1 || value === 'one' || value === 2 || value === 'two') { 

} 
Copy the code

You can change to

IndexOf () :

if ([1, 'one', 2, 'two'].indexOf(value) >= 0) { 

}
Copy the code

Or includes () :

if ([1, 'one', 2, 'two'].includes(value)) { 

}
Copy the code

10. Bitwise double non-operator (~~)

The bitwise double non operator (~~) is an alternative to the math.floor () method.

Const floor = Math. Floor (6.8); / / 6Copy the code

Is equivalent to

Const floor = ~ ~ 6.8; / / 6Copy the code

The bitwise double non-operator method only works with 32-bit integers. So for any number greater than this, math.floor () is recommended.

conclusion

Don’t use freewheeling coding styles. Otherwise you never know what might have happened. The same coding style should always be used throughout the team and the application code base to improve the readability of the code.