2

I saw this solution on codewars

    "strict mode";
let testarr = [true,true,false,true,true];

function countSheeps(arrayOfSheeps) {
  return arrayOfSheeps.filter(Boolean).length;
}

console.log(countSheeps(testarr))

How does this work? I thought that for the filter method to work a function must be passed into it rather than a data type or value. I tried this with an array of numbers and replaced the word "boolean" with "number" and also actual numbers eg 3. Yet this didnt work - So why does it work with boolean here?

3
  • Boolean object is not a data type. try typeof Boolean Commented Apr 3, 2020 at 14:45
  • 1
    Boolean is a function. Commented Apr 3, 2020 at 14:49
  • Oh okay so true and false are of data type boolean? Commented Apr 3, 2020 at 14:57

2 Answers 2

2

It utilizes the Boolean builtin, which can be used as a function.

Boolean(1); // => true
Boolean(0); // => false
Sign up to request clarification or add additional context in comments.

1 Comment

More accurately, "which is a function".
0

Boolean is a function, and .filter method takes function.

So it is same as like following code;


 "strict mode";
let testarr = [true,true,false,true,true];

function countSheeps(arrayOfSheeps) {
  return arrayOfSheeps.filter((sheep) => Boolean(sheep)).length;
}

console.log(countSheeps(testarr))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.