How to Check for Empty/Undefined/Null String in JavaScript
In JavaScript, one of the everyday tasks while validating data is to ensure that a variable, meant to be string, obtains a valid value.
This snippet will guide you in finding the ways of checking whether the string is empty, undefined, or null.
Here we go.
If you want to check whether the string is empty/null/undefined, use the following code:
let emptyStr;
if (!emptyStr) {
// String is empty
}
When the string is not null or undefined, and you intend to check for an empty one, you can use the length property of the string prototype, as follows:
Another option is checking the empty string with the comparison operator “===”.
It’s visualized in the following example:
Description of Strings in JavaScript
The JavaScript strings are generally applied for either storing or manipulating text. There is no separate for a single character. The internal format of the strings is considered UTF-16.
Another vital thing to know is that string presents zero or more characters written in quotes.
Usage of the Length Property in JavaScript
The “length” property is an essential JavaScript property, used for returning the number of function parameters. Also, the “length” property can be used for introspecting in the functions that operate on other functions.
Comparison Operators in JavaScript
Comparison operators are probably familiar to you from math.
So, they are the following:
- Less than (<) : returns true when the value on the left is less than the value on the right. In another way, it will return false.
- Greater than (>) : returns true when the value on the left is greater than the one on the right. Otherwise, it will return false.
- Less than or equal to (<=) : returns true when the value on the left is less than either equal to the value on the right. Otherwise, it will return false.
- Greater than or equal to (>=) : returns true when the value on the left is greater or equal to the one on the right. In another way, it will return false.
- Equal to (===) : returns true when the value on the left is equal to the one on the right. Otherwise, it will return false.
- Not equal to (!==) : returns true when the value on the left is not equal to the one on the right. In another way, it will return false.