For beginners, the most important thing is to learn how to write high-quality JS code. The way to learn is simple: read more, write more, summarize more:

  • Read more: Read the code written by the big boys and learn from their wisdom
  • Write more: the paper comes to sleep shallow, constantly knocking code to find their own problems, improve their own
  • Conclusion: I have been pursuing two learning methods — question driven learning and output failed input. Only after careful thinking and summarizing, can we find the details of many problems and truly master knowledge.

Of course, I am also a beginner in the front of the chicken, this blog content or cognitive error is a normal phenomenon, I hope the audience gentlemen don’t hesitate to comment. This blog is not completed in one time. Every time xiaozhu meets new problems, he will follow up the blog. Of course, you are welcome to add in the comments section!

0 What is code robustness?

When I read papers in school, I often came across robustness. When I studied in the company, I often heard others mention robustness of code. Therefore, I always felt surprised when I heard the discussion of bigwigs in weekly meetings.

Robustness, as the name suggests, is healthy and strong. This word is used to describe a person who is healthy and strong enough that a cold, a fall or an injury won’t keep him or her in bed. Take this word to describe the code, the truth is the same, when the code encounters various kinds of exception problems, such as reading a value is not the expected type, the query cannot be specified path, etc., the code will not easily die, but has its own set of measures.

If your code still has a tendency to crash and fall apart. Don’t worry, this article is a recipe for making your code stronger.

1 function

A function default parameters clever use

Scene:

Suppose we need to initialize the config object at the very beginning of the code

function initConfig(config) {
    config.map((item) = > {
        item.content = Number(item.content)
    })
}
Copy the code

If we accidentally forget to pass an argument to it, the browser will report the following error: config does not have a map method because config is undefined

Solutions:

We can assign a default value to a function argument

function initConfig(config = []) {
    config.map((item) = > {
        item.content = Number(item.content)
    })
}
Copy the code

Conclusion:

Here we can default to other types, such as strings, numbers, objects, etc., to improve the robustness of the code

2 Deconstruct the assignment

** Deconstruction: ** ES6 allows you to extract values from arrays and objects and assign values to variables in a pattern called deconstruction

A, arrays,

Scene:

Suppose we need an array of values for several variables, we use array deconstruction

function handleArr(arr) {
    let [a, b, c] = arr
    return a + b + c
}
Copy the code

The problem arises when the array we want to structure cannot be sure that the value is 100% correct, that is, not more or less

Solutions:

Assign default values to destruct assignments

function handleArr(arr) {
    let [a = 1, b = 2, c = 3] = [1.2.3]
    return a + b + c
}

const arr = [1.2]

handleArr(arr)	/ / 6
Copy the code

Conclusion:

Development often uses this method to pull out multiple values at once, but in cases where the deconstructed values do not exist, setting defaults improves code robustness

Second, the object

Scene:

Object scenes work the same way as arrays, but object deconstruction scenes are used more often.

Solutions:

Specify default values for object destruct assignments

function handleObj(obj) {
  const { name, list = [] } = obj
  if(name) {
    list.map((item) = > {
      console.log(item)
    })
  }
}

const obj = {
  name: 'add1'.list: [1.2.3]}Copy the code

Conclusion:

Objects can be destructed as strings, numbers, arrays, objects, etc. For different variable types, we need to specify different default values to ensure robustness of the code

3 Interface Request

The previous two points talked about not trusting the front-end’s own data, and not trusting the data coming from the back-end interface.

1. Back-end response data

Scene:

Assume that the backend specifies the following for the interface response

{
  code: 0.msg: "".data: []}Copy the code

Our front-end code might look something like this

async function handleData() {
  const { code, msg, data }  = await fetchList()
  data.map((item) = > {
    console.log(item)
  })
}
Copy the code

If the back-end interface is abnormal

  • The back-end interface fails, and the data retrieved is undefined
  • The data returned from the back end is not an array
  • .

The map method executed in the code will report an error

Solutions:

To prevent the interface from reverting back to the data field, we can specify default values for deconstruction

async function handleData() {
  const { code, msg, data = [] }  = await fetchList()
  data.map((item) = > {
    console.log(item)
  })
}
Copy the code

To prevent the interface from returning an array, we can check the type

async function handleData() {
  const { code, msg, data = [] }  = await fetchList()
  Array.isArray(data) && data.map((item) = > {
    console.log(item)
  })
}
Copy the code

Conclusion:

The data transmitted by the agreed interface may have non-existent data and abnormal errors of type pair. The processing of exceptions is added in the corresponding places to improve the robustness of the code

Second, exception capture

In addition to handling interface data, we also need to handle exceptions. See this blog post on exception Handling in JavaScript

4 lodash

Code robustness considerations are often overlooked when doing business development. We can use existing tool libraries to improve code robustness while also allowing developers to focus more on business logic development. The recommended tool library here is LoDash.

Document portal: Lodash Chinese documents

Select object

We mentioned above the use of deconstruction to get the value of an object. Here we can use the _.get() method without worrying about possible exceptions.

Methods:

_.get(object, path, [defaultValue])
Copy the code

Gets the value based on the path of the object. If the parse value is undefined, it will be replaced by defaultValue.

Parameters:

  1. bject (Object): The object to retrieve.
  2. path (Array|string): The path to get the property.
  3. [defaultValue] (*): If the parse value isundefined, this value will be returned.

The return value:

Returns the parsed value.