Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to write better JavaScript conditionality and matching conditions

2025-02-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)05/31 Report--

The knowledge of this article "how to prepare better JavaScript conditionality and matching conditions" is not understood by most people, so the editor summarizes the following contents, detailed contents, clear steps, and certain reference value. I hope you can get something after reading this article. Let's take a look at this "how to prepare better JavaScript conditionality and matching conditions" article.

1. Important things first. Small details, but important.

Don't use negative conditionals (which can be confusing). At the same time, conditional shorthand is used to represent the boolean value. There is no need to emphasize this, especially the negative conditional, which is not in line with the normal way of thinking.

Bad:

Const isEmailNotVerified = (email) = > {/ / implement} if (! isEmailNotVerified (email)) {/ / do something.} if (isVerified = true) {/ / do something.}

All right:

Const isEmailVerified = (email) = > {/ / implement} if (isEmailVerified (email)) {/ / do something.} if (isVerified) {/ / do something.}

Now, after sorting out the above, we can begin.

two。 For multiple conditions, use Array.includes

Suppose we want to check whether the car model is renault or peugeot in the function. Then the code might look like this:

Const checkCarModel = (model) = > {if (model = 'renault' | | model = =' peugeot') {console.log ('model valid');}} checkCarModel (' renault'); / / output 'model valid'

Considering that we only have two models, this seems acceptable, but what if we want to examine another model or several models? If we add more or statements, the code will become difficult to maintain and not clean enough. To make it more concise, we can rewrite the function like this:

Const checkCarModel = (model) = > {if (['peugeot',' renault'] .output (model)) {console.log ('model valid');}} checkCarModel (' renault'); / / output 'model valid'

The above code already looks beautiful. To further improve it, we can create a variable to hold the car model:

Const checkCarModel = (model) = > {const models = ['peugeot',' renault']; if (models.includes (model)) {console.log ('model valid');}} checkCarModel (' renault'); / / output 'model valid'

Now, if we want to check more models, we just need to add a new array element. In addition, if it is important, we can define the models variable outside the scope of the function and reuse it where needed. This approach allows us to centralize management and make maintenance easy, because we only need to change one location in the code.

3. Match all conditions, using Array.every or Array.find

In this case, we want to check that each car model is the one passed in the function. To achieve it in a more imperative way, we will do this:

Const cars = [{model: 'renault', year: 1956}, {model:' peugeot', year: 1968}, {model: 'ford', year: 1977}]; const checkEveryModel = (model) = > {let isValid = true; for (let car of cars) {if (! isValid) {break;} isValid = car.model = = model;} return isValid;} console.log (checkEveryModel (' renault')); / / output false

If you prefer to act in an imperative style, the above code may be good. On the other hand, if you don't care about what's going on behind it, you can rewrite the above function and use Array.every or Array.find to achieve the same result.

Const checkEveryModel = (model) = > {return cars.every (car = > car.model = model);} console.log (checkEveryModel ('renault')); / / output false

By using Array.find and making minor adjustments, we can achieve the same result. The behavior of the two is consistent because both functions perform callbacks for each element in the array and return false as soon as a falsy entry is found.

Const checkEveryModel = (model) = > {return cars.find (car = > car.model! = = model) = = undefined;} console.log (checkEveryModel ('renault')); / / output false

4. Match some of the conditions, using Array.some

Array.every matches all the conditions, and this method can easily check whether our array contains one or more elements. To do this, we need to provide a callback and return a Boolean based on the condition.

We can achieve the same result by writing a similar for...loop statement, just as we wrote before. But fortunately, there are cool JavaScript functions that can help us do this.

Const cars = [{model: 'renault', year: 1956}, {model:' peugeot', year: 1968}, {model: 'ford', year: 1977}]; const checkForAnyModel = (model) = > {return cars.some (car = > car.model = model);} console.log (checkForAnyModel (' renault')); / / output true

5. Return early instead of using the if...else branch

When I was a student, I was taught that a function should have only one return statement and return from only one place. If you deal with it carefully, this method is not bad. What I'm saying means that we should be aware that it can cause conditional nesting hell in some cases. If it is out of control, multiple branches and if...else nesting will make us feel very painful.

On the other hand, a deep return statement can cause problems if the code base is large and contains many lines of code. Now we all practice the principles of separation of concerns and SOLID, so it's rare to have too many lines of code.

An example is given to explain this problem. Suppose we want to display the model and year of production of the given vehicle:

Const checkModel = (car) = > {let result; / / first, define a result variable / / check whether there is a car if (car) {/ / check whether there is a car model if (car.model) {/ / check the year if (car.year) {result = `car: ${car.model}; Manufacturing year: ${car.year}; `;} else {result ='No car year' }} else {result ='No car model'}} else {result ='No car';} return result; / / our separate return statement} console.log (checkModel ()); / output'No car' console.log (checkModel ({year: 1988})); / / output'No car model' console.log (checkModel ({model: 'ford'})) / / output'No car year' console.log (checkModel ({model: 'ford', year: 1988})); / / output' Car model: ford; Manufacturing year: 1988 politics'

As you can see, even if the problem in this example is simple, the above code is too long. You can imagine what would happen if we had more complex logic. A large number of if...else statements.

We can reconstruct the above function, decompose it into several steps and make some improvements. For example, use ternary operators, including & & conditional, and so on. However, I'll skip straight to the end and show you how concise code can be with modern JavaScript features and multiple return statements.

Const checkModel = ({model, year} = {}) = > {if (! model & &! year) return'No car'; if (! model) return'No car model'; if (! year) return'No car year'; / / you can manipulate models or years here / / make sure they exist / / doSomething (model); / / doSomethingElse (year); return `Car model: ${model}; Manufacturing year: ${year}; ` } console.log (checkModel ()); / / output'No car' console.log (checkModel ({year: 1988})); / / output'No car model' console.log (checkModel ({model: 'ford'})); / / output' No car year' console.log (checkModel ({model: 'ford', year: 1988})); / / output' Car model: ford; Manufacturing year: 1988X'

In the refactoring version, we include deconstruction and default parameters. The default parameter ensures that we have a value available for deconstruction when we pass in the undefined. Note that if null is passed in, the function will throw an error. This is also the advantage of the previous method, because that method outputs'No car' when it passes in null.

Object deconstruction ensures that the function takes only what it needs. For example, if we include an additional property in a given vehicle object, that property is not available in our function.

Depending on your preference, developers will choose one of these ways. In practice, the code written is usually somewhere in between. Many people find if...else statements easier to understand and help them follow the flow of the program more easily.

6. Use indexes or maps instead of switch statements

Suppose we want to get a car model based on a given country.

Const getCarsByState = (state) = > {switch (state) {case 'usa': return [' Ford', 'Dodge']; case' france': return ['Renault',' Peugeot']; case 'italy': return [' Fiat']; default: return [];}} console.log (getCarsByState ()); / / output [] console.log (getCarsByState ('usa'); / / output [' Ford', 'Dodge'] console.log (getCarsByState (' italy')) / / output ['Fiat']

The appeal code can be refactored to completely remove the switch statement.

Const cars = new Map () .set ('usa', [' Ford', 'Dodge']) .set (' france', ['Renault',' Peugeot']) .set ('italy', [' Fiat']); const getCarsByState = (state) = > {return cars.get (state) | | [];} console.log (getCarsByState ()); / / output [] console.log (getCarsByState ('usa')) / / output ['Ford',' Dodge'] console.log (getCarsByState ('italy')); / / output [' Fiat']

Alternatively, we can create a class for each country that contains a list of available cars and use it when needed. But this is beside the point, the theme of this article is about conditionals. A more appropriate modification is to use the literals of the object.

Const carState = {usa: ['Ford',' Dodge'], france: ['Renault',' Peugeot'], italy: ['Fiat']}; const getCarsByState = (state) = > {return carState [state] | | [];} console.log (getCarsByState ()); / / output [] console.log (getCarsByState (' usa')); / / output ['Ford',' Dodge'] console.log (getCarsByState ('france')) / / output ['Renault',' Peugeot']

7. Use self-judging links and empty merges

At this point, I can finally say "finally". In my opinion, these two features are very useful for the JavaScript language. As a person from the C # world, it can be said that I use them a lot.

At the time of this writing, these have not been fully supported. Therefore, for code written in this way, you need to compile using Babel. You can look it up here in the self-judgment link and here in the empty merge.

Self-judging links allow us to deal with the tree structure without explicitly checking the existence of intermediate nodes. Empty merging ensures that there will be a default value when the nodes do not exist, which will work well with self-judging links.

Let's use some examples to support the above conclusion. At first, let's do it the old way:

Const car = {model: 'Fiesta', manufacturer: {name:' Ford', address: {street: 'Some Street Name', number:' 5555, state: 'USA'} / / get the car model const model = car & & car.model | |' default model'; / / obtain the manufacturer's address const street = car & & car.manufacturer & & car.manufacturer.address & & car.manufacturer.address.street | | 'default street' / / request a non-existent attribute const phoneNumber = car & & car.manufacturer & & car.manufacturer.address & & car.manufacturer.phoneNumber; console.log (model) / output 'Fiesta' console.log (street) / / output' Some Street Name' console.log (phoneNumber) / / output undefined

So, if we want to know if the vendor is from USA and print the result, the code goes like this:

Const checkCarManufacturerState = () = > {if (car & & car.manufacturer & & car.manufacturer.address & & car.manufacturer.address.state = = 'USA') {console.log (' Is from USA');}} checkCarManufacturerState () / / output'Is from USA'

I don't need to repeat how messy the code would be if the object structure were more complex. Many libraries, such as lodash, have their own functions as alternatives. But this is not what we want, what we want is to be able to do the same thing in native js. Let's take a look at the new approach:

/ / get the car model const model = car?.model? 'default model'; / / get the manufacturer's address const street = car?.manufacturer?.address?.street? 'default street'; / / check whether the car manufacturer is from USA const checkCarManufacturerState = () = > {if (car?.manufacturer?.address?.state =' USA') {console.log ('Is from USA');}}

It looks more beautiful and concise, and to me, it's very logical. If you want to know why you should use it? Instead of |, just think about what value can be used as true or false, and you may have unexpected output.

By the way, it's beside the point. Self-judging links also support DOM API, which is cool, which means you can do this:

Const value = document.querySelector ('input#user-name')? .value; the above is about "how to write better JavaScript conditionality and matching conditions". I believe you all have some understanding. I hope the content shared by the editor will be helpful to you. If you want to know more about the relevant knowledge, please 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.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report