In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "what are the rules for writing a good JS conditional statement". The content of the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "what are the rules for writing a good JS conditional statement"?
1. Use Array.includes in multiple judgments
Let's take a look at the following example:
/ / condition function test (fruit) {if (fruit = = 'apple' | | fruit = =' strawberry') {console.log ('red');}}
At first glance, the above example looks fine. What if we had more red fruits named cherry and cranberries? Are we going to expand conditional statements with more "|"?
We can rewrite conditional statements with Array.includes (Array.includes).
Function test (fruit) {const redFruits = ['apple',' strawberry', 'cherry',' cranberries']; if (redFruits.includes (fruit)) {console.log ('red');}}
We extract the condition of red fruit (red fruits) into an array. As a result, the code looks cleaner.
two。 Less nesting, Return as soon as possible
Let's extend the previous example to include two conditions.
If no parameter fruit is passed in, an error is thrown
Accept the quantity parameter and print it out when quantity is greater than 10:00
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's if (redFruits.includes (fruit)) {console.log ('red') / / condition 3: quantity greater than 10 if (quantity > 10) {console.log ('big quantity');} else {throw new Error (' No fruit');}} / / Test result test (null); / / error: No fruits test ('apple'); / / print: red test (' apple', 20); / / print: red, big quantity
In the above code, we have:
1 if/else statement filtered out invalid statements
3-tier if nested statements (condition 1, 2 & 3)
My personal rule is to Return as soon as possible when an invalid condition is found.
/ _ early Return _ / function test (fruit, quantity) {const redFruits = ['apple',' strawberry', 'cherry',' cranberries']; / / condition 1: throw error if (! fruit) throw new Error ('No fruiting') as early as possible; / / condition 2: must be red if (redFruits.includes (fruit)) {console.log ('red') / / condition 3: must be a high-quality if (quantity > 10) {console.log ('big quantity');}
As a result, we are missing a layer of nested statements. This coding style is very good, especially if you have long if statements (imagine you need to scroll to the bottom to know that there are else statements, which is not cool)
We can further reduce if nesting by inverting the judgment condition & return as soon as possible. Take a look at how we deal with judgment condition 2:
/ _ when invalid statements are found, Return _ / function test (fruit, quantity) {const redFruits = ['apple',' strawberry', 'cherry',' cranberries'] as soon as possible; / / condition 1: throw errors if (! fruit) throw new Error ('No fruits') as early as possible; / / condition 2: stop executing if (! redFruits.includes (fruit)) return when the fruit is not red Console.log ('red'); / / condition 3: must be a high-quality if (quantity > 10) {console.log (' big quantity');}}
By inverting judgment condition 2, our code avoids nested statements. This technique is very useful when we need to make a long logical judgment, especially when we want to be able to stop processing when the conditions are not met.
And it's not difficult to do so. Ask yourself, is this version (no nesting) better and more readable than the previous version (two layers of condition nesting)?
But for me, I will keep the previous version (with two layers of nesting). This is because:
The code is short and straightforward, with clearer nesting of if
Inverted judgment conditions may increase the burden of thinking (increase cognitive load)
Therefore, you should try to reduce nesting and return as soon as possible, but don't overdo it. If you are interested, take a look at an article on this topic and the discussion on StackOverflow.
Avoid Else, Return Early by Tim Oxley
StackOverflow discussion on if/else coding style
3. Use default parameters and deconstruct
I guess you may be familiar with the following code. In JavaScript, we always need to check the value of null / undefined and specify the default value:
Function test (fruit, quantity) {if (! fruit) return; / / if the quantity parameter is not passed, set the default value to 1 const Q = quantity | | 1; console.log (`We have ${Q} ${fruit}! `);} / / test results test ('banana'); / / We have 1 banana! Test ('apple', 2); / / We have 2 apple!
In fact, we can eliminate the variable Q by declaring the default function parameters.
Function test (fruit, quantity = 1) {/ / if the quantity parameter is not passed, set the default value to 1 if (! fruit) return; console.log (`We have ${quantity} ${fruit}! `);} / test results test ('banana'); / / We have 1 banana! Test ('apple', 2); / / We have 2 apple!
It's more intuitive, isn't it? Note that each declaration has its own default parameters.
For example, we can also assign a default value to fruit: function test (fruit = 'unknown', quantity = 1).
What if fruit were an object? Can we assign a default parameter?
Function test (fruit) {/ / print fruit value if (fruit & & fruit.name) {console.log (fruit.name);} else {console.log ('unknown');}} / / test results test (undefined); / / unknown test ({}); / / unknown test ({name:' apple', color: 'red'}); / / apple
Looking at the example above, we want to print the name property that might exist in the fruit object. Otherwise we will print unknown. We can avoid judging condition fruit & & fruit.name by default parameters and deconstruction.
/ / deconstruction-just get the name attribute / / assign it an empty object function test ({name} = {}) {console.log (name | | 'unknown');} / / test results test (undefined); / / unknown test ({}); / / unknown test ({name:' apple', color: 'red'}); / / apple
Since we only need the name attribute, we can deconstruct the parameter with {name}, and then we can use the variable name instead of fruit.name.
We also need to declare the empty object {} as the default value. If we don't, when you execute test (undefined), you will get an error that cannot be deconstructed for undefined or null. Because there is no name attribute in undefined.
If you don't mind using third-party libraries, there are some ways to reduce null checking:
Use the Lodash get function
Using Facebook's open source idx library (with Babeljs)
This is an example of using Lodash:
Function test (fruit) {/ / gets the property name. If the attribute name is not available, the default value is unknown console.log (_ .get (fruit, 'name',' unknown');} / / test results test (undefined); / / unknown test ({}); / / unknown test ({name: 'apple', color:' red'}); / / apple
You can run demo code in jsbin. In addition, if you are a fan of functional programming, you may choose to use the functional version of Lodash fp,Lodash (the method is changed to get or getOr).
4. Prefer object traversal to Switch statements
Let's take a look at the following example, where we want to print out the fruit according to color:
Function test (color) {/ / use conditional statements to find 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 looks error-free, but I found some encumbrance. Use object traversal to achieve the same result, and the syntax looks more concise:
Const fruitColor = {red: ['apple',' strawberry'], yellow: ['banana',' pineapple'], purple: ['grape',' plum']}; function test (color) {return fruitColor [color] | | [];}
Or you can use Map to achieve the same result:
Const fruitColor = new Map () .set ('red', [' apple', 'strawberry']) .set (' yellow', ['banana',' pineapple']) .set ('purple', [' grape', 'plum']); function test (color) {return fruitColor.get (color) | | [];}
Map is an object type implemented after the ES2015 specification that allows you to store the values of key and value.
But should we ban the use of switch statements? The answer is not to limit yourself. Personally, I will use object traversal as much as possible, but I don't strictly follow it, but in a way that makes more sense for the current scene.
Todd Motto has a more in-depth article on switch statements versus object traversal, where you can read
TL;DR; refactoring syntax
In the above example, we can ReFactor our code with Array.filter to achieve the same effect.
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) {return fruits.filter (f = > f.color = = color);}
There is more than one way to achieve the same results, and we have shown four above.
5. Use Array.every & Array.some for all / partial judgments
This last suggestion is more about using JavaScript Array's built-in methods to reduce lines of code. Looking at the code below, we want to check that all 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 are red for (let f of fruits) {if (! isAllRed) break; isAllRed = (f.color = = 'red') } console.log (isAllRed); / / false}
The code is so long! We can reduce the number of lines of code through Array.every:
Const fruits = [{name: 'apple', color:' red'}, {name: 'banana', color:' yellow'}, {name: 'grape', color:' purple'}]; function test () {const isAllRed = fruits.every (f = > f.color = = 'red'); console.log (isAllRed); / / false}
It's more concise now, isn't it? In the same way, if we want to test whether there is red fruit, we can use one line of Array.some code to do it.
Const fruits = [{name: 'apple', color:' red'}, {name: 'banana', color:' yellow'}, {name: 'grape', color:' purple'}]; function test () {/ / condition: any fruit is red const isAnyRed = fruits.some (f = > f.color = = 'red'); console.log (isAnyRed) / / true} Thank you for your reading. The above is the content of "what are the rules for writing JS conditional statements". After the study of this article, I believe you have a deeper understanding of what the rules for writing JS conditional statements have, and the specific usage still needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
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.