When working with TypeScript, you will frequently encounter various operators that help manage values and handle conditions. Among these, the nullish coalescing operator (??), the logical OR operator (||), and the double negation operator (!!) are particularly useful. Let’s break down each of them with clear definitions and examples, so you have a solid grasp of their functionalities.
The nullish coalescing operator (??) is a relatively new addition to JavaScript and TypeScript. It is used to provide a default value for expressions that are null
or undefined
. This operator is particularly beneficial when you want to assign a fallback value only when the left-hand side is specifically null
or undefined
, rather than when it is falsy (like 0
, false
, or ''
).
Example:
let userAge: number | null = null; let age = userAge ?? 18; console.log(age); // Output: 18
In this example, since userAge
is null
, the variable age
is assigned the value 18
.
The logical OR operator (||) is a more traditional operator that checks for truthy values. If the left-hand side expression evaluates to a truthy value, it returns that value; otherwise, it returns the right-hand side value. This operator can return any falsy value such as 0
, false
, ''
, null
, or undefined
. Thus, it is not ideal for scenarios where you want to differentiate between these falsy values.
Example:
let userScore: number = 0; let score = userScore || 10; console.log(score); // Output: 10
Here, although userScore
is 0
, the value of score
is assigned 10
because 0
is considered falsy.
The double negation operator (!!) is a simple yet powerful operator that converts a value to its boolean equivalent. The first negation (!
) converts the value to a boolean and inverts it, while the second negation inverts it back to its original boolean state. This operator is particularly useful when you need to evaluate a value and check if it is truthy or falsy.
Example:
let isActive: any = "yes"; console.log(!!isActive); // Output: true
In this case, the variable isActive
has a string value of "yes"
, which is truthy. Using the double negation operator, we confirm its truthy status, and the result is true
.
Operator | Purpose | Handles |
---|---|---|
?? | Returns the right-hand value if the left-hand value is null or undefined . | null, undefined |
!! | Converts a value to its boolean equivalent. | Truthy or falsy conversion |
By understanding these operators and their distinct functionalities, you can write more robust and understandable code in TypeScript. Remember, choosing the right operator depends on the specific requirements of your code and the values you are dealing with. Happy coding!
22/10/2024 | VanillaJS
15/10/2024 | VanillaJS
14/09/2024 | VanillaJS
22/10/2024 | VanillaJS
14/09/2024 | VanillaJS
25/07/2024 | VanillaJS
14/09/2024 | VanillaJS
22/10/2024 | VanillaJS
22/10/2024 | VanillaJS
14/09/2024 | VanillaJS