How to Check if Array has Empty String in Javascript

In this tutorial, you will learn how to check if array has empty string in javascript. An array is just a collection of type agnostic elements. A string that has a length of 0 is considered to be an empty string. For a beginner, it can be a bit tricky to find if an array has an empty string.

There are numerous ways to check if an array has an empty string. But for the sake of simplicity, we are going to use only the includes() method. This method returns true if the array contains the specified string, otherwise false.

In the following example, we have one global array users and it holds an array of strings.  Upon click of a button, we will check if the array has an empty string. Please have a look over the code example and steps given below.

HTML & CSS

  • We have 3 elements in the HTML file (div, button, and h1). The div element is just a wrapper for the rest of the elements.
  • The inner text for the button element is “Check” and for the h1 element is “Result”.
  • We have done some basic styling using CSS and added the link to our style.css stylesheet inside the head element.
  • We have also included our javascript file script.js with a script tag at the bottom.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="style.css">
    <title>Document</title>
</head>
<body>
    
    <div>
        <button>Check</button>
        <h1>Result</h1>
    </div>

    <script src="script.js"></script>
</body>
</html>
body {
    text-align: center;
}

div {
    display: inline-block;
}

button {
    display: inline-block;
    padding: 10px 20px;
}

Javascript

  • We have a global variable users and it holds an array of strings.
  • We have selected button and h1elements using the document.querySelector() method and stored them in btnCheck and result variables respectively.
  • We have attached the click event listener to the button element.
  • In the event handler function, we are passing an empty string to the includes() method. The includes() method will return if the array has an empty string.
  • As a result, we will get a Boolean value in return. Depending upon that, we will display True or False in the h1 element.
let users = ['Chris', 'Ryan', 'Tim', '', 'John'];

let btnCheck = document.querySelector('button');
let result = document.querySelector('h1');

btnCheck.addEventListener('click', () => {
 result.innerText = users.includes('') ? 'True' : 'False';
});