Ship internal tools in hours, not weeks. Real auth, users, jobs, audit logs, and cohesive UI included. Early access $249 $499 → [Get it now]

How to check if a string is empty in JavaScript

Checking if strings are empty is fundamental for form validation, data processing, conditional logic, and implementing features like required field validation or content display controls in JavaScript applications. With over 25 years of experience in software development and as the creator of CoreUI, I’ve implemented empty string checks extensively in components like form inputs, search bars, and content validators where ensuring data presence is crucial for user experience and application logic. From my extensive expertise, the most reliable and performant solution is checking the string’s length property against zero. This approach is direct, efficient, and handles the specific case of empty strings without ambiguity.

Use the length property to check if a string is empty by comparing it to zero.

const text = ''
const isEmpty = text.length === 0
// Result: true

The length property returns the number of characters in a string, so comparing text.length === 0 determines if the string contains no characters. In this example, an empty string '' has a length of 0, making the condition true. This method is precise and only returns true for completely empty strings, not for strings containing only whitespace. For strings with spaces like ' ', the length would be 3, not 0. This approach is faster than string comparison and more explicit than truthy/falsy checks.

1. Strict Equality Comparison

An alternative to length is comparing the string directly against an empty string literal using strict equality. This is equally performant and some developers find it more readable.

const text = ''
const isEmpty = text === ''
// Result: true

// Works correctly with non-empty strings
const greeting = 'hello'
const isGreetingEmpty = greeting === ''
// Result: false

// Strict equality prevents type coercion surprises
const zero = 0
const isZeroEmpty = zero === ''
// Result: false (correct — loose == would return true)

Using === instead of == is critical here. The loose equality operator == considers 0 == '' to be true due to type coercion, which can lead to subtle bugs. Always use strict equality when checking for empty strings to avoid these pitfalls.

2. Truthy/Falsy Checks

In JavaScript, an empty string is a falsy value. This means you can use a simple negation to check for emptiness, but be aware of the trade-offs.

const text = ''

// Falsy check — short and common
if (!text) {
  console.log('String is empty')
}

// However, falsy checks also catch null, undefined, 0, and false
const values = ['', null, undefined, 0, false, 'hello']
values.forEach(val => {
  if (!val) {
    console.log(`Falsy: ${val} (${typeof val})`)
  }
})
// Falsy: '' (string)
// Falsy: null (object)
// Falsy: undefined (undefined)
// Falsy: 0 (number)
// Falsy: false (boolean)

The !text pattern is concise but imprecise — it treats null, undefined, 0, and false the same as an empty string. Use it only when you intentionally want to catch all falsy values. For strict empty string detection, prefer text.length === 0 or text === ''.

3. Handling Whitespace-Only Strings

A common pitfall is treating whitespace-only strings as non-empty. User input often contains accidental spaces, tabs, or newlines that should be treated as empty.

const userInput = '   '

// length check fails — whitespace has length
const isEmptyByLength = userInput.length === 0
// Result: false (incorrect for most use cases)

// Trim first, then check
const isActuallyEmpty = userInput.trim().length === 0
// Result: true (correct)

// Practical helper function
const isBlank = (str) => !str || str.trim().length === 0

console.log(isBlank(''))        // true
console.log(isBlank('   '))     // true
console.log(isBlank('\t\n'))    // true
console.log(isBlank('hello'))   // false
console.log(isBlank(null))      // true
console.log(isBlank(undefined)) // true

The isBlank helper combines a falsy check with trim() to handle all edge cases: empty strings, whitespace-only strings, null, and undefined. This is the pattern we use in CoreUI React form components for required field validation. For more on trimming, see how to trim whitespace from a string in JavaScript.

4. Handling Nullish Values from APIs

Data from external APIs or databases often returns null or undefined instead of an empty string. You need to guard against these before checking length to avoid TypeError.

// This will throw: Cannot read properties of null
// const len = null.length

// Safe approach with optional chaining
const apiResponse = null
const isEmpty = !apiResponse?.length
// Result: true (no error)

// Nullish coalescing for default values
const name = apiResponse ?? ''
const isNameEmpty = name.length === 0
// Result: true

// Practical validation for API data
const validateField = (value) => {
  if (value == null) return false    // catches null and undefined
  if (typeof value !== 'string') return false
  return value.trim().length > 0
}

console.log(validateField('hello'))     // true
console.log(validateField(''))          // false
console.log(validateField(null))        // false
console.log(validateField(undefined))   // false
console.log(validateField(42))          // false

Optional chaining (?.) and nullish coalescing (??) are modern JavaScript features that make null-safe string checks concise and readable. The validateField function demonstrates a robust pattern for validating string data from untrusted sources.

5. Conditional Rendering Based on String Content

A common use case is showing or hiding UI elements based on whether a string has content. This pattern appears constantly in form validation and dynamic content display.

// Conditional message display
const errorMessage = ''
const successMessage = 'Order placed successfully'

const showError = errorMessage.length > 0
const showSuccess = successMessage.length > 0
// showError: false, showSuccess: true

// Array filtering — remove empty entries
const tags = ['react', '', 'javascript', '  ', 'css', '']
const validTags = tags.filter(tag => tag.trim().length > 0)
// Result: ['react', 'javascript', 'css']

// Form data cleanup before submission
const formData = {
  name: 'John',
  nickname: '',
  bio: '   ',
  email: '[email protected]'
}

const cleanData = Object.fromEntries(
  Object.entries(formData).filter(([, value]) =>
    typeof value === 'string' && value.trim().length > 0
  )
)
// Result: { name: 'John', email: '[email protected]' }

Filtering empty strings from arrays and objects is essential when processing form data or tag lists. Always trim before checking to catch whitespace-only values. For more on checking string content, see how to check if a string contains a substring in JavaScript.

6. Performance Comparison of Methods

When performance matters (e.g., processing large datasets), the method you choose can have a measurable impact.

const str = ''

// Method 1: length property (fastest)
str.length === 0

// Method 2: strict equality (equally fast)
str === ''

// Method 3: falsy check (fast, but imprecise)
!str

// Method 4: trim + length (slower — creates a new string)
str.trim().length === 0

// Method 5: regex (slowest — avoid for simple checks)
/^\s*$/.test(str)

For simple empty checks, length === 0 and === '' are virtually identical in performance. The trim().length approach is slower because trim() creates a new string, but the difference is negligible for individual checks. Only consider performance when processing thousands of strings in a loop.

Best Practice Note:

This is the same approach we use in CoreUI React components for form validation, conditional rendering, and data processing across our component ecosystem. Choose the right method for your context: use text.length === 0 for precise empty checks, !text when any falsy value should be treated as empty, and text.trim().length === 0 when whitespace-only strings should count as empty. For form validation, always trim user input first.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author

Subscribe to our newsletter
Get early information about new products, product updates and blog posts.

Answers by CoreUI Core Team