How to Check if a String is Empty in TypeScript?

As a developer, you may often encounter situations where you need to validate user input or ensure that a string variable contains a value before processing it further. In this tutorial, I will explain how to check if a string is empty in TypeScript using various methods with examples.

Empty Strings in TypeScript

In TypeScript, an empty string is a string that has no characters. It is represented by a pair of double quotes or single quotes with nothing in between. For example:

let emptyString1 = "";
let emptyString2 = '';

Both emptyString1 and emptyString2 are considered empty strings.

It’s important to note that a string containing only whitespace characters, such as spaces or tabs, is not considered an empty string. For instance:

let whitespaceString = "   ";

The whitespaceString variable contains whitespace characters and is not an empty string.

Check out Split a String by Comma in TypeScript

Check for Empty Strings in TypeScript using the Length Property

One of the simplest and most straightforward ways to check if a string is empty in TypeScript is by using the length property. The length property returns the number of characters in a string. If the length is zero, it means the string is empty.

Here’s an example:

function isStringEmpty(str: string): boolean {
  return str.length === 0;
}

let firstname = "John Doe";
console.log(isStringEmpty(firstname)); // Output: false

let emptyString = "";
console.log(isStringEmpty(emptyString)); // Output: true

In the above code, we define a function in TypeScript called isStringEmpty that takes a string parameter str. Inside the function, we check if the length of the string is equal to zero using the === operator. If the length is zero, the function returns true, indicating that the string is empty. Otherwise, it returns false.

We then call the isStringEmpty function with different string variables. When we pass "John Doe", the function returns false because the string has a length greater than zero. When we pass an empty string "", the function returns true.

Here is the exact output in the screenshot below:

Check if a String is Empty in TypeScript

Check out Convert an Array to a String in TypeScript

Check for Empty Strings using Comparison Operators

Another way to check if a string is empty in TypeScript is by using comparison operators. You can compare the string directly with an empty string literal to determine if it is empty.

Here’s an example:

function isStringEmpty(str: string): boolean {
  return str === "";
}

let email = "[email protected]";
console.log(isStringEmpty(email)); // Output: false

let emptyString = "";
console.log(isStringEmpty(emptyString)); // Output: true

In this approach, we compare the string str with an empty string literal "" using the === operator. If the string is equal to an empty string, the function returns true. Otherwise, it returns false.

I executed the above TypeScript code, and you can see the exact output in the screenshot below:

Check for Empty Strings in TypeScript using Comparison Operators

Check out Convert Boolean to String in TypeScript

Handle Null and Undefined Values

In TypeScript, it’s also important to consider the possibility of a string variable being null or undefined. These values indicate the absence of a value and should be handled separately from empty strings.

To check if a string is null or undefined, you can use the typeof operator in combination with comparison operators. Here’s an example:

function isStringEmpty(str: string | null | undefined): boolean {
  return str === null || str === undefined || str === "";
}

let name: string | null = null;
console.log(isStringEmpty(name)); // Output: true

let address: string | undefined;
console.log(isStringEmpty(address)); // Output: true

let emptyString = "";
console.log(isStringEmpty(emptyString)); // Output: true

let city = "New York";
console.log(isStringEmpty(city)); // Output: false

In this example, we modify the isStringEmpty function to accept a parameter of type string | null | undefined. This means the function can handle strings, null values, and undefined values.

Inside the function, we use the || (OR) operator to check if str is null, undefined, or an empty string. If any of these conditions are true, the function returns true. Otherwise, it returns false.

Read Convert Date to String Format DD/MM/YYYY in TypeScript

Real-World Example: Validate User Input

Now, let me show you a real example.

Let’s consider a real-world scenario where checking for empty strings is crucial. Suppose you are building a user registration form for a website, and you want to ensure that the user provides a valid username before submitting the form.

function validateUsername(username: string): boolean {
  if (username.trim().length === 0) {
    console.log("Please enter a valid username.");
    return false;
  }
  return true;
}

let username1 = "   ";
console.log(validateUsername(username1)); // Output: Please enter a valid username. \n false

let username2 = "JohnDoe";
console.log(validateUsername(username2)); // Output: true

In this example, we have a validateUsername function that takes a username parameter. Inside the function, we use the trim() method to remove any leading or trailing whitespace from the username. Then, we check if the trimmed username has a length of zero.

If the trimmed username is empty, we log an error message to the console and return false, indicating that the username is invalid. Otherwise, if the username is not empty, we return true.

When we call the validateUsername function with " " (a string containing only whitespace), it logs the error message and returns false. When we call it with "JohnDoe", it returns true, indicating a valid username.

Conclusion

In this tutorial, we explored different approaches to check if a string is empty in TypeScript, including using the length property and comparison operators. We also discussed the importance of handling null and undefined values separately from empty strings and provided a real-world example of validating user input.

You may also like:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.