How to Check if a String Is Empty, Undefined or Null in Javascript?
JavaScript provides a number of ways to check if a string is empty or if a variable is undefined or null. Here are a few examples:
- Check for an empty string:
let str = "";
if (str === "") {
console.log("string is empty");
}
- Check for undefined variable:
let val;
if (typeof val === "undefined") {
console.log("variable is undefined");
}
- Check for null variable:
let val = null;
if (val === null) {
console.log("variable is null");
}
- Check for empty or undefined string using ternary operator:
let str;
const result = str ? str : "default value";
console.log(result); // Output: "default value"
- Check for empty or undefined string using logical OR operator:
let str;
const result = str || "default value";
console.log(result); // Output: "default value"
Note: Keep in mind that the triple equal (===) operator is used to check for both type and value while the double equal (==) operator only checks for value.