4.13 Exercise: Counting Truthy Value
This exercise is about truthy and falsy values. Your task: create a function countTruthy that takes an array and returns the number of truthy elements in it. Before writing the function, let's quickly refresh what truthy and falsy mean.
Truthy vs falsy quick refresher
When a non-boolean value is used in a boolean context (an if condition for example), the JavaScript engine coerces it: it interprets the value as either truthy or falsy. The falsy values are undefined, null, 0, false, '' (empty string) and NaN. Every other value — for instance the string 'Toto' — is truthy.
Implementation
function countTruthy(array) {
let count = 0;
for (const value of array) {
if (value) count++;
}
return count;
}
const items = [1, 2, 3, 0, null, undefined, '', 'hello'];
console.log(countTruthy(items)); // 4
- The
for...ofloop iterates over the array values directly. - Writing
if (value)takes advantage of implicit boolean coercion — no need to compare against every falsy value manually. - The counter increments each time the value is truthy and is returned at the end.
The implementation stays concise because we trust the language's coercion rules. Avoid writing long chains like if (value !== null && value !== undefined && value !== 0 ...). See you in the next demonstration.