Could anyone please explain why this filter method only returns the true values?

const users = [
  {name: "shaun", premium: true},
  {name: "yoshi", premium: false},
  {name:"mario", premium: false},
  {name:"chun- li", premium: true}
];
 
const premiumUsers = users.filter((user) => {
  return user.premium ;
})
console.log(premiumUsers);

Im just curious as to why the filter method didnt return all of the values both false and true when the return is for user.premium and no distinction was made to actually filter out the false methods.

If I had to guess I would say that the filter method , when dealing with booleans automatically them as true unless they are false , but I am not sure.

The filter method evaluates the return value of the callback function as a boolean. If the returned value is truthy, the array item is kept. If it is falsy, the array item is removed. By returning user.premium it will remove the user if user.premium is falsy.

3 Likes

Exactly as said. Alternative could have been

users.filter({premium}) => premium) // destructuring and  filtering by premium