In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-12 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces the knowledge of "what are the tips for writing JavaScript". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
1. Async / await
If you are still stuck in callback hell, you should go back to 2014 to develop your code. Do not use callbacks unless absolutely necessary (such as third-party library needs or performance reasons). Promise is a great solution to callback hell, but as your code gets bigger and bigger, it also becomes less useful. My current solution is async / await, which greatly improves the readability and simplicity of the code. In all places where you use Promise you can replace it with await, where you need to return the Promise object, simply await it and return it, in order to ensure that it does not report an error, you need to add async at the beginning of the definition function. In fact, async / await is the grammatical sugar of Promise. Here is a simple example:
Async function getData () {const result = await axios.get ('https://dube.io/service/ping') const data = result.data console.log (' data', data) return data} getData ()
The await operator is used to wait for a Promise object. It can only be used in the asynchronous function async function. Async / await is part of ES2017, so you may need babel to compile your code. But now the mainstream browsers have already supported it.
two。 Asynchronous control flow
Often, we encounter the need to get multiple datasets and process each dataset individually, or to return a value after all asynchronous callbacks are complete. In these situations, this is how I deal with it:
For... Of
Suppose our page has multiple Pokemon (Pokemon), and we need to get detailed information about them. We don't want to wait until all the calls are over, especially if we don't know how many calls it has, we just want to update our dataset when it returns. You can use for... Of iterates through the array and executes async in the code block, so that the code will not continue to execute until each await execution succeeds.
It is important to emphasize that doing so can lead to performance bottlenecks (when there are many requests), but doing so like this can achieve the desired results. Take a look at the following example:
Import axios from 'axios'let myData = [{id: 0}, {id: 1}, {id: 2} {id: 3}] async function fetchData (dataSet) {for (entry of dataSet) {const result = await axios.get (`myData const newData = result.data updateData (newData) console.log (myData)}} function updateData (newData) {myData = myData.map (el = > {if (el.) Id = newData.id) return newData return el})} fetchData (myData)
This code is working properly, you can easily copy it to code sandbox to run.
Promise.all
What if you want to get all the details of Pokemon at the same time? You need to wait for all the requests to be completed and return, so simply use Promise.all:
Import axios from 'axios' let myData = [{id: 0}, {id: 1}, {id: 2} {id: 3}] async function fetchData (dataSet) {const pokemonPromises = dataSet.map (entry = > {return axios.get (`https://ironhack-pokeapi.herokuapp.com/pokemon/${entry.id}`)}) const results = await Promise.all (pokemonPromises) results.forEach (result = > {updateData (result.data)}) console.log (myData)} function updateData (newData) { MyData = myData.map (el = > {if (el.id = = newData.id) return newData return el})} fetchData (myData)
For...of and Promise.all are proposed by ES6 later, please make sure your environment is running.
3. Destructuring & default value
Let's go on to the example above and extract part of the code:
Const result = axios.get (`https://ironhack-pokeapi.herokuapp.com/pokemon/${entry.id}`)const data = result.data
There is an easy way to deconstruct some properties (values) from an array, or object. Like this:
Const {data} = await axios.get (...)
Note that when deconstructing, it is usually assigned a default value. This ensures that you don't get undefined and that you don't have to check variables manually.
Const {id = 5} = {} console.log (id) / / 5
This technique is also applied to function parameters. For example:
Function calculate ({operands = [1,2], type = 'addition'} = {}) {return operands.reduce ((acc) Val) = > {switch (type) {case 'addition': return acc + val case' subtraction': return acc-val case 'multiplication': return acc * val case' division': return acc / val}, ['addition' 'subtraction'] .initiate (type)? 0: 1)} console.log (calculate ()) / / 3console.log (calculate ({type:' division'})) / / 0.5console.log (calculate ({operands: [2,3,4], type: 'multiplication'})) / / 24
This example may seem a little confusing at first, but take a look at it. When we don't pass parameters to the function, we use the default value. Once we start passing parameters, only the default values of those parameters that are not passed are used. In this way, you reduce your handling of abnormal states.
4. True value & false value
When using default values, you don't have to do some extra checks on existing values. But it's great to know whether your variables are true or false. It can improve the extensibility of your code, be more persuasive and concise. I often see the following words:
If (myBool = true) {console.log (...)} / / ORif (myString.length > 0) {console.log (...)} / / ORif (isNaN (myNumber)) {console.log (...)}
In order to use these concise judgments, you need to fully understand the true values and false values in js. Here's an overview:
False value:
1. String, but the length is 0
two。 The number 0
3.false
4.undefined
5.null
6.NaN
True value
1. Empty array
two。 Empty object
3. Other valuable data. Note: when judging true / false values, you should also note whether you are using'= ='or congruent'= =', which often leads to bug. For me, it's often the number 0.
Logical Operation and Ternary operator
Logical operation
Logical operation is based on the judgment of multiple expressions, and it is noted that js is a lazy evaluation strategy. Logical operations generally return a Boolean value. The & & and | | operators return a value of the specified Operand. Take a look at this:
Console.log (true & & true) / / trueconsole.log (false & & true) / / falseconsole.log (true & & false) / / falseconsole.log (false & & false) / / falseconsole.log (true | | true) / / trueconsole.log (true | | false) / / trueconsole.log (false | true) / / trueconsole.log (false | | false) / / false
The logical operations are carried out in accordance with the following rules:
&: if the first value is false, it returns directly; if it is true, the second value is returned directly
|: if the first value is true, it is returned directly; if false, the second value is returned directly. |
Console.log (0 & & {a: 1}) / / 0console.log (false & &'a') / / falseconsole.log ('2' & & 5) / / 5console.log ([] | | false) / / [] console.log (NaN | | null) / / nullconsole.log (true | |'a') / / true
Ternary operator
The ternary operator is similar to the logical operation, but it has three parts:
Condition? Expr1: expr2
Condition is the part of condition judgment, which will get true value or false value.
The value returned when expr1 is conditionally judged to be true
Expr2 is the value returned when the conditional judgment is false.
For example:
Const lang = 'German'console.log (lang = =' German'? 'Hallo':' Hello') / / Halloconsole.log (lang? 'Ja':' Yes') / / Jaconsole.log (lang = = 'French'? 'Bon soir':' Good evening') / / Good evening
6. Optional Chaining
In the past, in the invocation of the Object attribute chain, it was easy to cause a Cannot read property xxx of undefined error later because a property did not exist. In order to confirm that this needs to be done to:
Let dataif (myObj & & myObj.firstProp & & myObj.firstProp.secondProp & & myObj.firstProp.secondProp.actualData) data = myObj.firstProp.secondProp.actualData
This is redundant. A new proposal is called Optional Chaining, which looks like this:
Const data = myObj?.firstProp?.secondProp?.actualData
I think it's the best way to check for nested properties, and the code is so concise.
This feature can be said to be very useful, but it is now in the stage-1 phase. You can use it by introducing the @ babel/plugin-proposal-optional-chaining plug-in into the .babelrc file.
7. Class properties & binding
Function binding is also a frequent task in JavaScript. Now, everyone should use the arrow function to automatically bind this to this class (there may be ambiguity here, first of all, there is no this and arguments in the arrow function, and the this here takes it as a parameter). If we don't use the arrow function, we need to bind this in the constructor, which is redundant when there are a lot of methods in the class. Therefore, it is recommended and advocated to use arrowhead functions in classes. Such as:
Class Counter extends React.Component {constructor (props) {super (props) this.state = {count: 0}} render () {return ({this.state.count} Increase Count)} _ increaseCount = () > {this.setState ({ Count: this.state.count + 1})}}
Use the arrow function to declare the method in the class, which is now in the stage-3 phase. You can use it by introducing the @ babel/plugin-proposal-class-properties plug-in into the .babelrc file.
8. Use parcel
As a front end, you will certainly encounter the situation of packaging and compiling code. It seems that webpack has been the standard for a long time. I've been using it since webpack 1, which is painful, of course. In order to understand all its configuration items, it took me countless hours to get it packaged and compiled properly. If I had a choice, I wouldn't study webpack. I happened to use parcel a few months ago, and I never found that the configuration could be so simple! You don't need to change anything to get the desired results, and of course you can modify the configuration items. It is also as configurable and fast as webpack or babel. If you don't know parcel, I definitely suggest you learn it!
Of course, now the mainstream standard is webpack,webpack 4, and the configuration is simple. You can learn about webpack after learning parcel, but you should start learning webpack 5 again.
9. Write more of your own code
When it comes to this topic, I have a lot to share and discuss. For css, many people prefer to use third-party component libraries like bootstrap. For JavaScript, I also see a lot of people like to use jQuery and some small validations, scrolling libraries, and so on. Although it is convenient to use the library, I strongly recommend that you implement it yourself instead of blindly installing the npm package. When it becomes a large library or framework, the whole team builds it, such as moment.js or react-datepicker, and it is difficult for you to change it when requirements change. So, you should write more of your own components. This will bring three important advantages:
You know exactly what happened to your code.
At the same time, in the process of doing it yourself, you can really begin to understand what programming is and how the code in the library works.
You can stop your code from getting bloated.
At the beginning, it is convenient to use the npm package. You can spend more time implementing your business logic. But when that package doesn't work as expected, you change it, and you have to spend more time reading its API to use it. When it is a library (component) that you implement yourself, you can customize it 100% with your own use cases.
This is the end of the content of "what are the tips for writing JavaScript". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.