DEV Community

Randy Rivera
Randy Rivera

Posted on

Removing An array With a Falsy Value

function bouncer(arr) {
  return arr;
}

bouncer([7, "ate", "", false, 9]);
Enter fullscreen mode Exit fullscreen mode
  • We should remove all falsy values from an array.
  • Falsy values in JavaScript are false, null, 0, "", undefined, and NaN.

Hint:

// regular for loop that I use which is 
for (let i = 0; i < arr.length: i++) { // which reads indexes.
// This new method while watching videos which is 
 for (let elem of arr {
 console.log(elem); 
 }
// basically its a loop that goes through all the elements themselves instead of going through the indexes.
 if (false) {
 console.log("hello") 
; // it wont call out hello because false is a falsey value
Enter fullscreen mode Exit fullscreen mode
  • Answer:
function bouncer(arr) {
  let result = [];
  for (let elem of arr) {
    if (elem) result.push(elem);
  }
  return result;
}

bouncer([7, "ate", "", false, 9]); // will display [7, "ate", 9]
Enter fullscreen mode Exit fullscreen mode

Top comments (0)