Working with 'null' & 'undef'
Part of the Introduction To TypeScript section of Coddy's JavaScript journey — lesson 9 of 73.
The undefined type represents a variable that has been declared but not assigned a value, or a function that doesn't explicitly return anything. The null type, on the other hand, represents an intentional absence of value - it's explicitly assigned to indicate "no value."
let userName: string | null = null; // Intentionally no value
let userAge: number | undefined; // Declared but not assignedTypeScript's strict null checking helps prevent common runtime errors by forcing you to handle these cases explicitly. When you have a variable that might be null or undefined, you must check for these values before accessing properties or methods.
function getLength(text: string | null): number {
if (text === null) {
return 0; // Handle the null case
}
return text.length; // Safe to use string methods
}Challenge
EasyCreate a function named getStringLength that accepts a parameter of type string | null and returns a number.
The function should handle both cases:
- If the parameter is a string, return its length
- If the parameter is
null, return0
Test your function by calling it with the following values and printing the results:
- Call
getStringLength("Hello TypeScript") - Call
getStringLength(null) - Call
getStringLength("TS")
Print each result on a separate line in the order listed above.
Try it yourself
// TODO: Write your code here
// Create the getStringLength function that accepts string | null and returns number
// Test the function with the required values and print resultsThis lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Introduction To TypeScript
1Getting Started with TS
What is TypeScript?Why Use TypeScript?Your First TypeScript CodeCompilation Process & ErrorsRecap: Introduction to TS4Working with Functions
Typing Params & Return ValuesTyping Arrow FunctionsThe 'void' Return TypeOptional Parameters with '?'Default Parameter ValuesTyping Rest ParametersDefining Function TypesRecap: Building Typed Funcs2Core Types
Basic Types: str, num, booleanThe 'any' Type: Escape HatchThe 'unknown' TypeWorking with 'null' & 'undef'Type Inference in ActionExplicit Type AnnotationsRecap: Core Types Practice5Types: Aliases, Unions & Inter
Type Aliases for PrimitivesUnion Types ('|')Working with Union TypesLiteral TypesIntersection Types ('&')Combining Type AliasesRecap: Advanced Type Combos3Data Structure: Arrays & Tuple
Typed Arrays'readonly' Modifier for ArraysWhat is a Tuple?Declaring and Accessing TuplesDestructuring TuplesReadonly TuplesMulti-dimensional Typed Arrays Spread Operator with ArraysRecap: Arrays and Tuples