Menu
Coddy logo textTech

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 assigned

TypeScript'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 icon

Challenge

Easy

Create 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, return 0

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 results
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Introduction To TypeScript