How can I check if a variable is empty in JavaScript?

For example, in the case of response.photo from a JSON object, how can I check if it’s empty, especially when it may contain empty data cells?

To check if a variable is either null or undefined, you can use the == (loose equality) comparison, as it will match both null and undefined:

if (response.photo == null) {
  console.log("photo is null or undefined");
}

== null will return true for both null and undefined, which is useful when you just want to check if the variable is not set.

@heenakhan.khatri to check if a variable is an empty string, you can simply use the length property.

if (response.photo === "" || response.photo == null) {
  console.log("photo is an empty string or null/undefined");
}

This checks whether response.photo is an empty string (“”) or null/undefined.

Hi @heenakhan.khatri, If the response photo could be an array, you can check if it’s empty by checking its length:

if (Array.isArray(response.photo) && response.photo.length === 0) {
  console.log("photo is an empty array");
}

Array.isArray() checks if the variable is an array, and .length === 0 checks if the array is empty.