How to Remove Empty Elements from Array in Javascript

In this video tutorial, you will learn how to remove empty elements from array in javascript.

HTML:

<!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>Remove</button>
    <h1>Length</h1>
    <ul></ul>
  </div>

  <script src="script.js"></script>
</body>
</html>

 

CSS:

body {
    text-align: center;
}

div {
    display: inline-block;
}

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

li {
    font-weight: bold;
    font-size: 20px;
    list-style: none;
    margin-left: -40px;    
}

 

Javascript:

let users = ['Marks', 'James', 'Jane', null, , 'Peter', 'Ronald'];

function addUsers(){
    let template = users.map(user => `<li>${user}</li>`).join('\n');
    document.querySelector('ul').innerHTML = template;
    document.querySelector('h1').innerText = users.length;
}

addUsers();

let btnRemove = document.querySelector('button');

btnRemove.addEventListener('click', () => {
    users = users.filter(user => user !=  null);
    addUsers();
});

 

  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •