8 tips for writing JavaScript code

8 tips for writing JavaScript code

Front-end Pioneer

8 tips for writing JavaScript code

1. Generate numbers in the specified interval

Sometimes it is necessary to create an array within a certain number range. For example, when choosing a birthday. The following is the simplest way to achieve it.


let start = 1900,
    end = 2000;
[...new Array(end + 1).keys()].slice(start);
// [ 1900, 1901, ..., 2000]

// 也可以这样,但是大范围结果不稳定
Array.from({ length: end - start + 1 }, (_, i) => start + i);

2. Use the values ​​in the value array as the parameters of the function

Sometimes we need to put the value in the array first, and then pass it as a function parameter. Using ES6 syntax, the value can be extracted from the array only by the spread operator (...): [arg1, arg2] => (arg1, arg2).


const parts = {
  first: [0, 2],
  second: [1, 3],
};

["Hello", "World", "JS", "Tricks"].slice(...parts.second);
// ["World", "JS", "Tricks"]

This technique is applicable to any function, please continue to item 3.

3. Use the values ​​in the value array as the parameters of the Math method

When you need to find the maximum or minimum value of a number in an array, you can do as follows:


// 查到元素中的 y 位置最大的那一个值
const elementsHeight =  [...document.body.children].map(
  el => el.getBoundingClientRect().y
);
Math.max(...elementsHeight);
// 输出最大的那个值

const numbers = [100, 100, -1000, 2000, -3000, 40000];
Math.min(...numbers);
// -3000

4. Flatten nested arrays

Array has a method called Array.flat, which requires a depth parameter to flatten nested arrays (default value is 1). But if you don't know what to do with depth, you only need to use Infinity as a parameter at this time. There is also a very useful flatMap method.


const arrays = [[10], 50, [100, [2000, 3000, [40000]]]];
arrays.flat(Infinity);
// [ 10, 50, 100, 2000, 3000, 40000 ]

5. Prevent code crash

If there is unpredictable behavior in the code, the consequences are unpredictable, so it needs to be dealt with.

For example, when the property you want to get is undefined or null, you will get a TypeError error.

If your project code does not support optional chaining, you can do this:


const found = [{ name: "Alex" }].find(i => i.name === 'Jim');
console.log(found.name);
// TypeError: Cannot read property 'name' of undefined

Can be avoided like this


const found = [{ name: "Alex" }].find(i => i.name === 'Jim') || {};
console.log(found.name);
// undefined

However, it depends on the situation. There is no problem with small-scale code processing. It can be processed without much code.

6. A good way to pass parameters

In ES6, you can treat template literals as parameters of functions without parentheses. This is very useful when formatting or converting text.


const makeList = (raw) =>
  raw
    .join()
    .trim()
    .split("\n")
    .map((s, i) => `${i + 1}. ${s}`)
    .join("\n");

makeList`
Hello, World
Hello, World
`;

// 1. Hello
// 2. World

7. Exchange the values ​​of variables like a juggling

By destructuring the assignment syntax, variables can be exchanged easily.


let a = "hello";
let b = "world";

// 错误 ❌
a = b
b = a
// { a: 'world', b: 'world' }

// 正确 ✅
[a, b] = [b, a];
// { a: 'world', b: 'hello' }

8. Mask string

Sometimes we need to mask a part of the string, of course, not just to do this operation on the password. In the following code, a part of the string is obtained by substr(-3), that is, 3 characters from the end of the string, and then fill the remaining positions with the characters you like (for example, *)


const password = "hackme";
password.substr(-3).padStart(password.length, "*");
// ***kme

Conclusion

You also need to keep the code tidy when coding, usually pay attention to the skills accumulated in the coding, and pay attention to the new features of JavaScript.

Guess you like

Origin blog.51cto.com/15077562/2609660