Do not allow to push empty or undefined string respectively into my array

Viewed 24

Despite I added the condition in my if query that inputs value should not be undefined, when i click on the add button when there is no input or only white space created with the space bar a empty string is pushed into my array and will be displayed from my arrays length counter. How can this be possible even though a empty string like "" or " " is undefined? How can I implement my desired function?

<input>
<button id="add">add</button>
<button id="remove">remove</button>
    <p></p>
    <span>0</span>
window.onload = function () {
  const inp = document.querySelector("input");
  const btn = document.getElementById("add");
  const addBtn = document.getElementById("add");
  const rBtn = document.getElementById("remove");
  const p = document.querySelector("p");
  const sp = document.querySelector("span");
  let toDo = [];

  addBtn.addEventListener("click", () => {
    if (inp.value != undefined) {
      console.log(inp.value)
      toDo.push(inp.value);
      sp.innerHTML = toDo.length;
    }
    p.innerHTML = toDo.join(" ");
    inp.value = "";
    inp.value = "";
  });

  rBtn.addEventListener("click", () => {
    inp.value = "";
    p.innerHTML = "";
    toDo = [];
    sp.innerHTML = "0";
    console.clear()
  });
};
1 Answers

If the input is empty this doesn't mean it's value equal to undefined, you need to trim() the value and check if the length is not equal to zero, with that if the input value is empty or just white spaces, it will not be pushed in the array.

    if (inp.value.trim().length !== 0) {
      console.log(inp.value)
      toDo.push(inp.value);
      sp.innerHTML = toDo.length;
    }

Related