I’m Garfield at 🐱. If you like my article, please feel free to like it and share it

Summary of some common development JS tips to make your code more elegant!

1. Assign a Boolean value to a variable based on the condition judgment

Let’s start with some code:

handleFormChange(e) {
  let isUpload;
  if (e.target.value === 'upload') {
    isUpload = true;
  } else {
    isUpload = false; }}Copy the code

Many colleagues in projects write this, but in fact the expressions == and === can be assigned directly to variables:

handleFormChange(e) {
  let isUpload = (e.target.value === 'upload');
}
Copy the code

If you want to invert it, it’s easy:

handleFormChange(e) {
  letisManual = (e.target.value ! = ='upload');
}
Copy the code

2. Conditionally add attributes to objects

You can use the expansion operator to conditionally add attributes to an object:

const condition = true;
const person = {
  id: 1.name: "dby". (condition && {age: 12})};Copy the code

If condition is true, {age: 16} is added to the object; If condition is false, it expands false and has no effect on the object

3. Conditionally add elements to the array

This is the CRA Webpack configuration source:

module.exports = {
  plugins: [
    new HtmlWebpackPlugin(),
    isEnvProduction &&
      new MiniCssExtractPlugin(),
    useTypeScript &&
      new ForkTsCheckerWebpackPlugin(),
  ].filter(Boolean),}Copy the code

The MiniCssExtractPlugin will be added only if isEnvProduction is true. When isEnvProduction is false false is added to the array, so filter is used

4. Deconstruct assignments

Deconstructing assignments is convenient and often used in projects, which can be divided into the following two scenarios:

  • Object/array deconstruction;
  • Function parameter deconstruction;

Here are four common techniques.

1) Deep deconstruction

Most of the time we only deconstruct one level, but actually deconstructing assignments can be deeply deconstructed:

let obj = {
  name: "dby".a: {
    b: 1}}const { a: { b } } = obj;
console.log(b); / / 1
Copy the code

2) Use aliases when deconstructing

If the key name returned from the back end is not what we want, we can use an alias:

const obj = {
  // This key name is too long, we want to change it
  aaa_bbb_ccc: {
    name: "dby".age: 12.sex: true}}const { aaa_bbb_ccc: user } = obj;
console.log(user); // { name: "dby", age: 12, sex: true }
Copy the code

3) Use default values for deconstruction

The default value can be used for object deconstruction, if the object’s property value is strictly equal to undefined:

fetchUserInfo()
  .then(({ aaa_bbb_ccc: user = {} }) = > {
    // ...
  })
Copy the code

The above three features can be combined

4) Use short circuit to avoid errors

Destruct assignment is useful, but it is important to note that the object to be destructed cannot be undefined or null, otherwise an error will be reported. Therefore, it is necessary to give a default value to the object to be deconstructed:

const {a,b,c,d,e} = obj || {};
Copy the code

5. Expand operators

Matches two arrays or two objects with an expansion:

const a = [1.2.3];
const b = [1.5.6];
// bad
const c = a.concat(b);
// good
const c = [...new Set([...a,...b])];

const obj1 = { a:1 };
const obj2 = { b:1 };
// bad
const obj = Object.assign({}, obj1, obj2);
// good
constobj = { ... obj1, ... obj2 };Copy the code

One thing to note here is that object and array merges look like… But actually there is a difference.

The ES2015 extension operator is specified for arrays and function arguments, but not for objects, and is based on for… Of, so the expanded objects can only be arrays, strings, sets, maps and other iterable objects. If you expand ordinary objects into arrays, an error will be reported.

Object… This is an ES2018 Object expansion syntax, equivalent to object. assign:

Babeljs. IO/docs/en/bab…

6. Check whether the attribute exists in the object

You can use the in keyword to check for the presence of an attribute in an object:

const person = { name: "dby".salary: 1000 };
console.log('salary' in person); // true
console.log('age' in person); // false
Copy the code

However, the in keyword is not secure and will include attributes from the prototype, for example:

"hasOwnProperty" in {}; // true
"toString" in {}; // true
Copy the code

Therefore, the following methods are recommended:

Object.prototype.hasOwnProperty.call(person, "salary"); // true
Copy the code

But the above problem is too long, every time you use it to write this kind of trouble. ECMA has proposed a new Object. HasOwn (), equivalent to the Object. The prototype. The hasOwnProperty. Call (alias) :

Object.hasOwn(person, "salary"); // true
Copy the code

Developer.mozilla.org/en-US/docs/…

Note that there are compatibility issues with this syntax (Chrome > 92), but polyfill is safe to use if configured correctly.

7. Object traversal

Many colleagues on the project would write something like this:

for (let key in obj) {
  if (Object.prototype.hasOwnProperty.call(obj, key)) {
    // ...}}Copy the code

Keys or Object.entries into an array can be traversed by array methods, and traverses are their own properties, not the prototype.

Object.keys(obj).forEach(key= > {
  // ...
})

Object.entries(obj).forEach(([key, val]) = > {
  // ...
})
Copy the code

Retort: Sometimes you don’t want to iterate over the entire object. Array methods can’t break the loop.

If you use find to find items that match the criteria, you will not continue to iterate.

Object.keys(obj).find(key= > key === "name");
Copy the code

8. Use includes to simplify if judgements

You often see code like this in projects:

if (a === 1 || a === 2 || a === 3 || a === 4) {
    // ...
}
Copy the code

You can use includes to simplify the code:

if ([1.2.3.4].includes(a)) {
    // ...
}
Copy the code

9. Convert Number to String

Number converts to String:

let num = 1;
num.toString(); / / "1"
String(num); / / "1"
num + ""; / / "1"
`${num}`; / / "1"
Copy the code

String to Number:

let s = "233";
+s; / / 233
Number(s); / / 233
parseInt(s); / / 233
Copy the code

10. The string contains less than two bits of zeros

This requirement is common in development. For example, calling the Date API might get a Date of only one digit:

let date = new Date().getDate(); / / 3
Copy the code

General practice:

if (data.toString().length == 1) {
    date = ` 0${date}`; }Copy the code

Using String. Prototype. Slice:

// Add a 0 in front of each digit and cut off the last two digits
date = ` 0${date}`.slice(-2);
Copy the code

Using String. Prototype. PadStart:

// If the length of the string is smaller than the value of the first argument, the second argument is added
date = `${date}`.padStart(2.0);
Copy the code

reference

My code is simple

If you know how to use ES6, use it!

A developer summed up these 15 elegant JavaScript tips