8
Author: Apoorv Tyagi
Translator: Frontend Xiaozhi
Source: dev

There are dreams and dry goods. WeChat search [Moving to the World] Follow this brushing wisdom who is still doing dishes in the early morning.

This article GitHub https://github.com/qq449245884/xiaozhi has been included, the first-line interview complete test site, information and my series of articles.

Don't talk nonsense, just arrange it directly.

1. Use number separators

This is one of the most commonly used operators when I need to deal with large numbers. When a separator is used in a number (only one _ ), it looks better than a number without a separator. E.g:

let number = 98234567

Can be written like this

let number = 98_234_567

And it also applies to any other base numbers.

const binary = 0b1000_0101;
const hex = 0x12_34_56_78;

A few notes:

Cannot be used after the leading 0

let num= 0_12

It is not allowed to appear at the end of the number.

let num= 500_

2. Always use semicolons

It is a good practice to terminate the line with a semicolon. If you forget, you won't be warned, because in most cases it will be inserted by the JavaScript parser, but relying on automatic semicolon insertion (ASI) is discouraged.

Google , Airbnb and jQuery JS style guide, it is also recommended to use a semicolon to terminate the line.

3. Don't forget var

When you assign a value to a variable for the first time, make sure that you have not assigned a value to an undeclared variable.

Assignment to undeclared variables will automatically result in the creation of a global variable. Avoid global variables ❌

Global variables are easily overwritten by other scripts. For example, if two separate parts of an application define global variables with the same name but different uses, it may cause unpredictable errors, and debugging such problems will be a terrible experience.

Usually the variables in a function should be local so that they will be released when you finish executing the function.

4. Delete vs Splice

Use splice instead of delete to delete an item from an array. Using delete will delete the properties of the object, but will not reset the index array or update its length.

Delete

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

Please note that in fact it is not set to undefined , but the attribute is removed from the array to make it look like undefined . You can control and myArray then you will know it.

image.png

Splice

Splice() actually deletes the element, resets the index, and changes the length of the array.

> myArray = ['a', 'b', 'c', 'd']
  ["a", "b", "c", "d"]
> myArray.splice(0, 2)
  ["a", "b"]
> myArray
  ["c", "d"]
delete method should be used to delete object attributes.

5. map vs for loop

Use the map() function to traverse the items of the array

var squares = [1,2,3,4].map(function (val) {  
    return val * val;  
}); 

//  [1, 4, 9, 16]

Immutability -The original array will not be affected. This is beneficial in situations where the original array is still needed elsewhere. for loop can of course be implemented, but this requires more code and needs to update our new array as part of the loop operation. On the other hand, map() can maintain this kind of cleanliness, because you only need to work in one role and still maintain the immutability.

Cleaner code- same thing, the map can almost always be written with less code for It can sometimes be written clearly on one line, while for requires at least two lines or generally three lines, and includes parentheses. In addition, scope isolation and reducing the number of variables you need and the reduced size make the code objectively cleaner.

6. Rounded numbers

toFixed() method uses fixed-point notation to format a value.

var pi =3.1415;
pi = pi.toFixed(2);  // pi will be equal to 3.14
Note: toFixed() returns a string instead of a number.

7. Use console.table

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

You can use console.table to display objects in the form of a table.

image.png

8. Avoid using try-catch

Each time the catch clause is try-catch structure will create a new variable in the current scope, in which the caught exception object is assigned to a variable.

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  
    } 
}

The second way of writing

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  
} 

When an error occurs, the first one lets you continue the loop, and the second one exits the loop. If the exception thrown by your code is not severe enough to stop the entire program, then the first one is suitable.

9. Multiple condition checks

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

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

} 

indexOf():

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

}

includes():

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

}

10. Double not bitwise operator (~~)

The double not bit operator can be seen as a substitute for the Math.floor()

const floor = Math.floor(6.8); // 6 

It can also be written like this:

const floor = ~~6.8; // 6

The double not-bit operator method is only applicable to 32-bit integers. Therefore, for any higher number than this, it is recommended to use Math.floor()

Summarize

Final advice-don't use random coding styles. There must be an implementation standard.

~End, I am Xiaozhi. After finishing, I am ready to order LoL, remember to like and follow, and get rich~


possible bugs after code deployment cannot be known in real time. In order to solve these bugs afterwards, a lot of time was spent on log debugging. By the way, I would like to recommend a useful BUG monitoring tool Fundebug .

Original: https://dev.to/apoorvtyagi/javacript-tips-and-best-practices-48ma

comminicate

There are dreams and dry goods. search 160fe021194325 [Great Move to the World] Follow this brushing wit who is still doing dishes in the early morning.

This article GitHub https://github.com/qq449245884/xiaozhi has been included, the first-line interview complete test site, information and my series of articles.


王大冶
68k 声望104.9k 粉丝