4 JavaScript Operators with question mark

Tram Ho

1. ?? operator

In Javascript, ?? is known as a ‘nullish coalescing’ operator. This operator will return the first value if it is not null or undefined, otherwise it will return the second value.

When assigning default values ​​to a variable, JavaScript developers often rely on the OR operator, like so.

Above we have created a moneyAmount function moneyAmount in charge of returning the user’s current balance. We used the || operator to identify users without an account. However, what does that mean when the user doesn’t have an account? It would be more accurate to consider no account as null instead of 0 because bank accounts can exist without money (or negative money). In the above example, the || operator see 0 as a falsy value so don’t register that our user has an account with 0 $. We fix it with the operator ??

Operator ?? allows us to assign default values ​​while removing falsy and empty strings.

2. ??= operator

The ??= operator is also known as the ‘logical nullish assignment’ operator and is closely related to what we learned earlier.

The assignment operator will only assign a new value if the current value is null / undefined. The example above highlights how this operator demonstrates the assignment syntax for nullish.

One notable difference here is the way in which the above functions treat null values. Default parameters override default values ​​with null arguments, and ??= operator does not. Both the default parameter and the Specify nullish will not overwrite the value for undefined

3 ?. operator

Operator ‘Optional chaining’ ?. Allows developers to read property values ​​nested within a sequence of objects without having to explicitly validate each property along the way to the desired property. When a reference is nullish, the expression stops and returns an undefined value.

Now, let’s incorporate everything we’ve learned so far and add Tuesday to our new travel plan!

We have now created a function that adds plans for an object that currently does not have the nested property of tuesday.location. We have also used nullish operators to provide default values. This function will accept false values ​​like ‘0’ as a valid parameter. Which means our budget can be set to 0 without any errors.

4. ? operator

Operator ? has 3 operands: a condition, an expression that will do if the condition is true, and an expression that will do when the condition is false.


Operator ? can also be used in assigning values ​​to variables

We can also use it to reproduce the behavior of the nullish assignment.

Can we use operators ? to refactor the above example
Share the news now

Source : Viblo