Borislav Hadzhiev
Last updated: Jul 25, 2022
Check out my new book
Use the length
property to check if a string is empty, e.g.
if (str.length === 0) {}
. If the string's length is equal to 0
, then it's
empty, otherwise it isn't empty.
const str = ''; if (typeof str === 'string' && str.length === 0) { console.log('string is empty'); } else { console.log('string is NOT empty') }
If you consider an empty string one that contains only spaces, use the trim()
method to remove any leading or trailing whitespace before checking if it's
empty.
const str = ' '; if (typeof str === 'string' && str.trim().length === 0) { console.log('string is empty'); } else { console.log('string is NOT empty'); }
trim()
method removes the leading and trailing spaces from a string. If the string contains only spaces, trim()
returns an empty string.To check if a string is truthy and contains one or more characters, pass the
string to an if
statement.
const str = 'hello'; if (str) { // if this code block runs // 👉️ str is NOT "", undefined, null, 0, false, NaN console.log("string is truthy") }
The code in the if
block wouldn't run if the str
variable is set to an empty
string, undefined
, null
, 0
, false
or NaN
.
You can also check that the value is not equal to an empty string.
const str = ''; if (typeof str === 'string' && str !== '') { // if this code block runs // 👉️ string is NOT empty }
if
statement. We first check if the contents of the str
variable are of type string
. This is very important, because we shouldn't compare an empty string to a value of a different type.We used the &&
(AND) operator to specify that both conditions have to be true
for the if
block to run.
This approach wouldn't work for a string that contains an empty space " "
. If
you need to handle strings that contain only spaces, use the trim()
method.
const str = ' '; if (typeof str === 'string' && str.trim() !== '') { // if this code block runs // 👉️ string is NOT empty }
str
variable contains a string and then we call the String.trim
method. If we try to call the trim
method on a variable that is set to undefined
or null
, we'd get an error.The String.trim method returns a new string with the whitespace from both ends of a string removed.
const str = ' hello '; const trimmed = str.trim(); console.log(trimmed) // 👉️ 'hello'
We can check if a string is empty by accessing its length
property. If the
string has a length
of 0
, then it is empty.
const str = 'hello'; if (typeof str === 'string' && str.length !== 0) { // if this code block runs // 👉️ string is NOT empty console.log("string is NOT empty") }
length
property on a variable that is undefined
or null
you'd get an error. Make sure that the variable is set to a string
before you try to access its length
property.