编程知识 cdmana.com

Four unheard of powerful JavaScript operators

Preface

New features , Look at it and forget it , Maybe not often

Did you spend an afternoon reading Mozilla Documents ? If you have , You'll know that , There's a lot about it online JavaScript Information about . This makes it easy for people to ignore some of the more remote JavaScript The operator .

However , Just because these operators are uncommon doesn't mean they're not powerful ! They look very similar in grammar , But be sure to read every one of them , Because they work differently .

Let's find out !

1. ?? The operator

stay JavaScript in ,?? The operator is called nullish coalescing Operator ( Zero merge operator ). If the first parameter is not null/undefined, This operator will return the first parameter , otherwise , It will return the second parameter . Let's take an example .

null?? 5// => 53?? 5// => 3


When a variable is assigned a default value ,JavaScript Developers traditionally rely on logic OR Operator , Such as this .

var prevMoney = 1var currMoney = 0var noAccount = nullvar futureMoney = -1function moneyAmount(money) {return money || `You currently do not own an account in the bank`}console.log(moneyAmount(prevMoney)) // => 1console.log(moneyAmount(currMoney)) // => `You currently do not own an account in the bank`console.log(moneyAmount(noAccount)) // => `You currently do not own an account in the bank`console.log(moneyAmount(futureMoney))//  => -1


Above we created a function moneyAmount, Responsible for returning the user's current balance . We used || Operator to identify users without accounts . However , What does it mean when a user doesn't have an account ? It is more accurate to treat no account as null, instead of 0, Because bank accounts can exist without ( Or negative ) Money situation . In the example above ,|| Operator will 0 As a fake value , So we didn't register with one of our users 0 The dollar account . Let's use nullish coalescing Operator to solve this problem .

var currMoney = 0var noAccount = nullfunction moneyAmount(money) {return money ?? `You currently do not own an account in the bank`} moneyAmount(currMoney) // => 0 moneyAmount(noAccount) // => `You currently do not own an account in the bank`

In a nutshell ,?? Operator allows us to assign default values , Ignore at the same time 0 And an empty string .

2. ??= The operator

??= Also known as logical null value assignment operator , It's closely related to what we learned before . Let's see how they are connected .


var x = nullvar y = 5console.log(x ??= y) // => 5console.log(x = (x ?? y)) // => 5

This assignment operator assigns a new value only if the current value is empty or undefined . The above example emphasizes that this operator is essentially a syntax sugar for null value assignment . Next , Let's see how this operator differs from the default parameter .

function gameSettingsWithNullish(options) {  options.gameSpeed ??= 1  options.gameDiff ??= 'easy' return options}function gameSettingsWithDefaultParams(gameSpeed=1, gameDiff='easy') {return{gameSpeed, gameDiff}}gameSettingsWithNullish({gameSpeed: null, gameDiff: null}) // => { gameSpeed: 1, gameDiff: 'easy' }gameSettingsWithDefaultParams(null, null) // => { gameSpeed: null, gameDiff: null }


There is a noticeable difference between the above functions when dealing with null values . The default parameter will override the default value with null Parameters ,nullish Assignment operators don't . Default parameters and nullish Assignment does not override undefined values . Read more here .

3. ?. The operator

Optional chain operators ?. Allow developers to read property values embedded in the chain of objects , Instead of explicitly validating each reference . When a reference is empty , The expression stops evaluating and returns an undefined value . Let's take a look at an example .


var travelPlans  = {  destination: 'DC',  monday: {    location: 'National Mall',    budget: 200}};const tuesdayPlans = travelPlans.tuesday?.location;console.log(tuesdayPlans) // => undefined

Now? , Let's incorporate everything we've learned so far into our new travel plan !

function addPlansWhenUndefined(plans, location, budget) {if(plans.tuesday?.location == undefined) {var newPlans = {      plans,      tuesday: { location: location ?? "Park", budget: budget ?? 200},};} else{    newPlans ??= plans; //will only override if newPlans is undefined    console.log("Plans have already been added!");}return newPlans;}var newPlans = addPlansWhenUndefined(travelPlans, "Ford Theatre", null);console.log(newPlans) // => { plans://{ destination: 'DC',// monday: { location: 'National Mall', budget: 200 } },// tuesday: { location: 'Ford Theatre', budget: 200 } }newPlans = addPlansWhenUndefined(newPlans, null, null) // logs => Plans have already been added!// returns => newPlans object


We've now created a function , take plans Add to a property that currently has no nesting tuesday.location The object of . We also used nullish Operator to provide the default value . This function will accept '0' Such an imaginary value is used as a valid parameter . This means that our budget can be set to 0, And there will be no mistakes .

4. ? The operator

Ternary operator ? : Three operands are required , An expression to be executed if the condition is true , And an expression to execute if the condition is false . Let's see how it works .

function checkCharge(charge) {     return(charge > 0) ? 'Ready for use': 'Needs to charge' }console.log(checkCharge(20)) // => 'Ready for use'console.log(checkCharge(0)) // => 'Needs to charge'

If you are in the JavaScript It took some time on , You may have seen ternary operators . However , Did you know that ternary operators can be used to assign variables ?

var budget = 0var transportion = (budget > 0) ? 'Train': 'Walking' console.log(transportion) // => 'Walking'

We can even use it to replicate nullish The act of assignment .

var x = 6var x = (x !== null|| x !== undefined) ? x : 3console.log(x) // => 6

Now let's summarize this behavior by creating a function !

function nullishAssignment(x,y) {return(x == null|| x == undefined) ? y : x}var x = nullishAssignment(null, 8) // => 8var y = nullishAssignment(4,8) // => 4

Before finishing , Let's use the ternary operator to reconstruct the function in the previous example .



4 It's an unheard of power JavaScript The operator



translator :@ Floating

original text :

4 It's an unheard of power JavaScript The operator


spring data jpa Advanced applications

SpringMVC Parameter unified verification method

SpringBoot RabbitMQ Reliable sending and receiving of messages

Springboot Interface idempotency is based on token Implementation scheme

SpringBoot Develop your own @Enable function

SpringBoot2 Integrate OAuth2 Resource Authentication ( Protect )

SpringBoot2 Integrate OAuth2 Achieve unified authentication

springboot Implementation of optimistic lock based on database

版权声明
本文为[Old age wine]所创,转载请带上原文链接,感谢
https://cdmana.com/2020/12/20201224090938736E.html

Scroll to Top