How to Check if a String Is Empty, Undefined or Null in Javascript?

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:

  1. Check for an empty string:
let str = "";

if (str === "") {
  console.log("string is empty");
}
  1. Check for undefined variable:
let val;

if (typeof val === "undefined") {
  console.log("variable is undefined");
}
  1. Check for null variable:
let val = null;

if (val === null) {
  console.log("variable is null");
}
  1. Check for empty or undefined string using ternary operator:
let str;

const result = str ? str : "default value";
console.log(result); // Output: "default value"
  1. 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.

Latest Questions

javascript How to Check if a Javascript Array Includes a Given Value? javascript How to Completely Uninstall Nodejs, and Reinstall From Scratch on Mac OS X? javascript How to Map Values of a Javascript Object to a New Object Using a Function?