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 a variable that does not have a value.
These methods validate the empty or filled string. The outcomes of this post are described here:
- Using the Strict Equality (===) Operator for Empty/Undefined/Null String
- Using the Length Property for Empty/Undefined/Null String
- Conversion Variable to Boolean to Check the Empty/Undefined/Null String
In this method, the strict equality operator is used to check the undefined, empty, or null string. The operator returns the true output if the user inputs the string data type; otherwise, the operator returns the false output.
console.log("" === "")// check the empty value
console.log("__" ==="") // check the operator value
After the execution of the code, the output is given below.
let string2 = ""; // check the empty string
console.log(string1.length === 0)
console.log(string2.length === 0)
In the code, string1, string2 are used to store different data types. In the end, the property of length is utilized to compute whether the string is empty or not and return the output.
The above display indicates that the second value in the output is true, which validates that the string is empty.
While other values return false, which shows the strings are filled.
Method 3: Converting String to Boolean to Check the Empty/Undefined/Null String
In the third method, empty/undefined/null strings are checked by converting the variable into a Boolean value. The code is given below with descriptions.