Distinguishing Between ? and ||Ī prevalent misconception is that the nullish coalescing operator (?) functions identically to the logical OR operator (||). It simplifies the code and enhances readability. The nullish coalescing operator proves highly beneficial when working with optional properties or values that may be undefined in certain cases. Since userName is null, the displayName is assigned the value of defaultName, which is “Guest”. In essence, the operator returns the right-hand side value as a fallback if the left-hand side is null or undefined.Ĭonsider this example: const userName: string | null = null Ĭonst displayName = userName ? defaultName Ĭonsole.log(displayName) // Output: "Guest" Conversely, if the left-hand operand holds a non-null, non-undefined value, that value is returned. The nullish coalescing operator (?) is a logical operator that evaluates the left-hand operand and returns the right-hand operand if the left-hand operand is null or undefined. Understanding the Nullish Coalescing Operator (?) Understanding the Nullish Coalescing Operator (?).
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |