Check empty/undefined/null string in JavaScript
To check if a JavaScript string is truthy and contains one or more characters, pass the string to an if statement.
if (strValue) {
//strValue is NOT an empty string (""), undefined, null, 0, false, NaN
}
There is not a standard function in JavaScript to check for empty string (""), undefined, null, 0, false or NaN values. However, there is the concept of truthy and falsy values in JavaScript. Values that coerce to true in conditional statements are called truth values and those that resolve to false are called falsy.
To check for a falsy value:
if (!strValue) {
// strValue is an empty string (""), undefined, null, 0, false, NaN
}
JavaScript === Operator
If you want to check for exactly an empty string, compare for strict equality against "" using the JavaScript "===" operator:
if (strValue === "") {
// strValue is an empty string
}
Using JavaScript length Property
You can check for the length of the string by adding its length property. If the length is equal to zero, it means that the string is empty else not empty.
const strValue="";
if(strValue.length === 0){
//strValue is an empty string
}
else{
// strValue is NOT an empty string
}
Difference between empty, null, undefined and NaN

An empty string ("") represents a string of zero length, while a null string shows that it does not contain any value. Moreover, the undefined term refers to it exists but hasn't been given a value yet and NaN is not a valid number . According to ES specification, the following values will evaluate to false in a conditional context -
- empty string ("")
- null
- undefined
- NaN
- if ("") {}
- if (null) {}
- if (undefined) {}
- if (NaN) {}
Related Topics
- JavaScript Popup Boxes
- Opening a new window in JavaScript
- How to Create Drop-Down Lists in JavaScript
- How do I include a JavaScript file in another JavaScript file?
- Print the content of a Div using JavaScript/jQuery
- How to get the current URL using JavaScript ?
- How to Detect a Mobile Device with JavaScript/jQuery
- How to validate an email address in JavaScript
- JavaScript Array Iteration
- How to Remove a Specific Item from an Array in JavaScript
- What is JavaScript closures?
- How To Remove a Property from a JavaScript Object
- How to get selected value from Dropdown list in JavaScript
- How do I get the current date in JavaScript?
- How to Open URL in New Tab | JavaScript
- How to delay/wait/Sleep in code execution | JavaScript
- How to round to at most 2 decimal places | JavaScript
- How to convert string to boolean | JavaScript
- How to check undefined in JavaScript?
- How To Copy to Clipboard | JavaScript
- How to encode a URL using JavaScript?
- How to force Input field to enter numbers only | JavaScript
- How to create multiline string in JavaScript