In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces how to write a better JavaScript related knowledge, the content is detailed and easy to understand, the operation is simple and fast, has a certain reference value, I believe that everyone after reading this how to write a better JavaScript article will have a harvest, let's take a look at it.
Using Array.includes to handle multiple conditions
Take a chestnut:
/ / conditional statement function test (fruit) {if (fruit = = 'apple' | | fruit = =' strawberry') {console.log ('red');}}
At first glance, it doesn't seem like a big problem to write like this.
However, what if we want to match more red fruits, such as cherries and cranberries? Do we have to use more | | to extend this statement?
We can rewrite the above conditionals using Array.includes.
Function test (fruit) {/ / extract conditions into an array const redFruits = ['apple',' strawberry', 'cherry',' cranberries']; if (redFruits.includes (fruit)) {console.log ('red');}}
We extract all the red fruits (conditions) into an array, which makes our code look cleaner.
Write less nesting and return as soon as possible
Let's add two conditions to the previous example:
If no fruit is provided, throw an error
If the quantity of the fruit is greater than 10, print it out.
Function test (fruit, quantity) {const redFruits = ['apple',' strawberry', 'cherry',' cranberries']; / / condition 1:fruit must have a value if (fruit) {/ / condition 2: it must be red if (redFruits.includes (fruit)) {console.log ('red') / / condition 3: there must be a large number of if (quantity > 10) {console.log ('big quantity');} else {thrownewError (' No fruit');}} / / Test result test (null); / / error report: No fruitstest ('apple'); / / print: redtest (' apple', 20) / / print: red,big quantity
Let's take a closer look at the code above. We have:
1 if/else statement to filter invalid conditions
3 layers of if statements are nested (condition 1, 2-3).
Personally, one of the general rules I follow is to return as soon as possible when an invalid condition is found.
/ return as soon as possible when an invalid condition is found /
Function test (fruit, quantity) {const redFruits = ['apple',' strawberry', 'cherry',' cranberries']; / / condition 1: throw error if (! fruit) thrownewError ('No fruiting') as early as possible; / / condition 2: must be red if (redFruits.includes (fruit)) {console.log ('red') / / condition 3: there must be a large number of if (quantity > 10) {console.log ('big quantity');}
In this way, we write one less layer of nesting. This is a good code style, especially when the if statement is very long (imagine that you have to scroll to the bottom to know that there is an else statement, isn't it a little uncomfortable).
If we reverse the condition, we can further reduce the level of nesting. Notice the following condition 2 statement to see how this is done:
/ return as soon as possible when an invalid condition is found /
Function test (fruit, quantity) {const redFruits = ['apple',' strawberry', 'cherry',' cranberries']; if (! fruit) thrownewError ('No fruit'); / / condition 1: throw error if (! redFruits.includes (fruit)) return; / / condition 2: return console.log ('red') directly when fruit is not red / / condition 3: there must be a large number of if (quantity > 10) {console.log ('big quantity');}}
By reversing the condition of condition 2, our code is now no longer nested.
This technique is useful when our code has a long logical chain and wants to stop executing the subsequent process when a condition is not met.
However, there are no hard rules that require you to do so. It's up to you, is this version of the code (no nesting) better and more readable for you than the previous version (condition 2 is nested)?
If it were me, I would choose the previous version (condition 2 is nested). The reason is:
The code is short and straightforward, and a nested if makes the structure clearer.
Conditional reversal will lead to more thinking process (increasing cognitive burden).
Therefore, always pursue less nesting and return earlier, but don't overdo it.
Use function default parameters and deconstruction
I guess you may be familiar with the following code, where we often need to check null / undefined and assign default values in JavaScript:
Function test (fruit, quantity) {if (! fruit) return; const q = quantity | | 1; / / if no quantity is provided, the default is 1 console.log (`We have ${Q} ${fruit}! `);} / / Test result test ('banana'); / / We have 1 bananatesting (' apple', 2); / / We have 2 apple!
In fact, we can remove the variable Q from the default parameter of the function.
Function test (fruit, quantity = 1) {/ / if no quantity is provided, default is 1 if (! fruit) return; console.log (`We have ${quantity} ${fruit}! `);} / / Test result test ('banana'); / / We have 1 bananadiagnostic test (' apple', 2); / / We have 2 apple!
Is it more simple and straightforward?
Note that all function parameters can have their default values. For example, we can also assign a default value to fruit:
Function test (fruit = 'unknown', quantity = 1).
What if fruit is an object (Object)? Can we still use the default parameters?
Function test (fruit) {/ / if there is a value, print out if (fruit & & fruit.name) {console.log (fruit.name);} else {console.log ('unknown');}} / / Test result test (undefined); / / unknowntest ({}); / / unknowntest ({name:' apple', color: 'red'}); / / apple
Looking at the above example, when the fruit name attribute exists, we want to print it out, otherwise print "unknown".
We can avoid writing fruit & & fruit.name conditions by default parameters and deconstructing assignments.
/ / deconstruct-- only get the name attribute
/ / default parameter is empty object {}
Function test ({name} = {}) {console.log (name | | 'unknown');} / / Test result test (undefined); / / unknowntest ({}); / / unknowntest ({name:' apple', color: 'red'}); / / apple
Since all we need is the name attribute of fruit, we can deconstruct it using {name}, and then we can use the name variable in our code to replace fruit.name.
We also use {} as its default value.
If we don't do this,
When you execute test (undefined), you will get an error Cannot destructure property name of 'undefined' or' null'.
Because there is no name attribute on undefined.
(translator's note: this is not accurate, actually because deconstruction only applies to objects (Object), not because there is no name attribute on undefined (nor on empty objects). Reference deconstruction assignment-MDN)
If you don't mind using third-party libraries, there are some ways to help reduce null (null) checks:
Use the Lodash get function
Use Facebook's open source idx library (with Babeljs).
Here is an example of using Lodash:
/ / use the _ method provided by the lodash library
Function test (fruit) {/ / gets the value of the attribute name. If not, set it to the default unknown console.log (_ .get (fruit, 'name',' unknown');} / / Test result test (undefined); / / unknowntest ({}); / / unknowntest ({name: 'apple', color:' red'}); / / apple
You can run the demo code here.
In addition, if you prefer functional programming (FP), you can choose to use the functional version of Lodash of Lodash fp-- (the method name is changed to get or getOr).
It may be a better choice than switch,Map / Object.
Let's look at the following example, where we want to print all kinds of fruits according to color:
Function test (color) {/ / use switch case to find the corresponding color of fruit switch (color) {case 'red': return [' apple', 'strawberry']; case' yellow': return ['banana',' pineapple']; case 'purple': return [' grape', 'plum']; default: return [];}}
/ / Test results
Test (null); / / []
Test ('yellow'); / / [' banana', 'pineapple']
The above code doesn't look wrong, but personally, it looks lengthy. The same result can be achieved by the literal amount of the object, and the syntax is more concise:
/ / use the literal amount of the object to find the fruit of the corresponding color
Const fruitColor = {red: ['apple',' strawberry'], yellow: ['banana',' pineapple'], purple: ['grape',' plum']}; function test (color) {return fruitColor [color] | | [];}
Alternatively, you can use Map to achieve the same effect:
/ / use Map to find the fruit of the corresponding color
Const fruitColor = newMap () .set ('red', [' apple', 'strawberry']) .set (' yellow', ['banana',' pineapple']) .set ('purple', [' grape', 'plum']); function test (color) {return fruitColor.get (color) | | [];}
Map is a new object type introduced by ES2015 that allows you to store key-value pairs.
Does that mean we should ban the use of switch statements? Don't limit yourself.
I myself will use the literal amount of objects whenever possible, but that doesn't mean I don't use switch, depending on the scene.
In the above example, we can actually use Array.filter to achieve the same effect by refactoring our code.
Const fruits = [{name: 'apple', color:' red'}, {name: 'strawberry', color:' red'}, {name: 'banana', color:' yellow'}, {name: 'pineapple', color:' yellow'}, {name: 'grape', color:' purple'}, {name: 'plum', color:' purple'}] Function test (color) {/ / use Array filter to find the fruit return fruits.filter of the corresponding color (f = > f.color = = color);}
There is never more than one way to solve the problem. For this example, we show four implementation methods.
Coding is fun!
Use Array.every and Array.some to handle full / partial fulfillment of conditions
The last tip is more about using new (and not very new) JavaScript array functions to reduce the number of lines of code.
Looking at the following code, we want to check that all the fruits are red:
Const fruits = [{name: 'apple', color:' red'}, {name: 'banana', color:' yellow'}, {name: 'grape', color:' purple'}]; function test () {let isAllRed = true; / / condition: all fruits must be red for (let f of fruits) {if (! isAllRed) break; isAllRed = (f.color = = 'red') } console.log (isAllRed); / / false}
This code is too long! We can reduce the code through Array.every.
Const fruits = [{name: 'apple', color:' red'}, {name: 'banana', color:' yellow'}, {name: 'grape', color:' purple'}]; function test () {/ / condition: (short form) all fruits must be red const isAllRed = fruits.every (f = > f.color = = 'red'); console.log (isAllRed); / / false}
It's much clearer, right?
Similarly, if we want to check whether at least one fruit is red, we can use Array.some to do it with just one line of code.
Const fruits = [{name: 'apple', color:' red'}, {name: 'banana', color:' yellow'}, {name: 'grape', color:' purple'}]; function test () {/ / condition: at least one fruit is red const isAnyRed = fruits.some (f = > f.color = = 'red'); console.log (isAnyRed) / / true} this is the end of the article on "how to write a better JavaScript". Thank you for reading! I believe you all have a certain understanding of "how to write a better JavaScript". If you want to learn more, you are welcome to follow the industry information channel.
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.