JavaScript Check if Array or String is Empty

Home /

Table of Contents

Empty String

An empty string is a string that has a length of 0 and contains no characters. In JavaScript, you can create an empty string by assigning an empty set of double quotes (“”) or single quotes (”) to a variable. For example:

JavaScript
let emptyString = "";
let anotherEmptyString = '';

Check empty string in JavaScript

In JavaScript, you can check if a string is empty by using the ‘length’ property of the string. If the ‘length’ is equal to 0, then the string is empty. Here is an example:

JavaScript
let str = "";
if (str.length === 0) {
    console.log("The string is empty.");
}

You can also check for an empty string using the ‘.trim()’ method .

JavaScript
let str = " ";
if (str.trim().length === 0) {
    console.log("The string is empty.");
}

Another way to check for an empty string is to use the ‘!’ operator which will return true if the string is empty and false if it is not.

JavaScript
let str = "";
if (!str) {
    console.log("The string is empty.");
}

You can use any of the above method to check if a string is empty or not.

About .trim()

In JavaScript, the ‘.trim()’ method is used to remove whitespace from the beginning and end of a string. It can be called on a string variable and does not take any arguments. For example, if you have the string ” Hello World! ” and you call the ‘.trim()’ method on it, the resulting string will be “Hello World!” with all the whitespace removed from the beginning and end of the original string.

Check if Array is Empty in JavaScript

In JavaScript, you can check if an array is empty using the ‘length‘ property of the array. Here’s an example:

JavaScript
const myArray = [];

if (myArray.length === 0) {
  console.log("Array is empty");
} else {
  console.log("Array is not empty");
}

In the above code, we define an empty array ‘myArray‘. Then, we check the length of the array using the ‘length‘ property. If the length of the array is equal to zero, we print “Array is empty”. Otherwise, we print “Array is not empty”.

Note that an empty array in JavaScript is considered to be a truthy value, so you can also use the empty array as a condition in an ‘if‘ statement without explicitly checking its length:

JavaScript
const myArray = [];

if (myArray) {
  console.log("Array is not empty");
} else {
  console.log("Array is empty");
}

In this case, if the array is empty, the condition evaluates to ‘false‘, so the ‘else‘ block is executed and “Array is empty” is printed.

Share The Tutorial With Your Friends
Twiter
Facebook
LinkedIn
Email
WhatsApp
Skype
Reddit
Other Recommended Article