Functional Programming - Implement the filter Method on a Prototype

Tell us what’s happening:
I can’t figure out what is happening in the example solutions if part of the code. It also seems like that if part of the code is even missing one closing bracket there.
It’s clear what I’m pushing into the newArray but what does the callback check here?

If it is finding out if the value is truthy, how does it do it?
I know that the item % 2 returns either 0 or 1 (falsy or truthy) depending if item is even or odd, but how does the computer know that I want to push x into newArray when there is no clear indication what has to happen before executing the code inside the curly brackets as there is in if (x > y) { newArray.push(x) };.
There is just a blank space between callback and push commands which doesn’t make sense.

I tried reading through different ways to create if statement but I have only found out about ternary operations written in more compact manner and not one of the sites I have seen cover this type of if statement.

Your code so far

Array.prototype.myFilter = function(callback) {
  const newArray = [];
  // Only change code below this line

  for (let x of this) {
    if (callback(x)) newArray.push(x);
  }
  
  // Only change code above this line
  
  return newArray;
};

console.log([23, 65, 98, 5, 13].myFilter(item => item % 2))


Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36

Challenge: Functional Programming - Implement the filter Method on a Prototype

Link to the challenge:

First of all:

 if (callback(x)) newArray.push(x);.

is the same as writing:

 if (callback(x)) {
   newArray.push(x)
 };.

If an if statement only has a single executable line, then you can leave off the surrounding curly brackets.

Secondly, an if statement’s code block will execute if the if statement’s condition is truthy. The computer only knows if the value is truthy, then execute either the next line (without surrounding curly brackets) or the next block of code (within surrounding curly brackets).

Thank you for your fast and very clear response!

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.