Home > Back-end >  Can someone help me interpret the if statement in this javascript code?
Can someone help me interpret the if statement in this javascript code?

Time:06-25

function filterArray(array, callback) {
  const newArray = [];
  for (let i = 0; i < array.length; i  = 1) {
    if (callback(array[i])) newArray.push(array[i]);
  }
  return newArray;
}

I'm confused by the syntax. Typically what I've seen so far is

if (condition) {
  // code to be executed
}

where condition is some boolean statement which will run the code shown if condition = true.

But, in this if statement, there is no boolean, nor is there code to be executed after the conditonal statement. I have no clue what it means. Thanks in advance for any help interpeting it.

CodePudding user response:

(callback(array[i])) this part is the condition. newArray.push(array[i]) this is what happens when the condition is met. It just looks so close together.

if (callback(array[i])) 
{
   newArray.push(array[i])
}

Does same thing.

CodePudding user response:

There is a boolean, namely the value returned from calling the function callback with argument array[i]. (To be precise: The interpretation of the returned value as a truth value according to the JavaScript language specs - this is what is meant by 'truthy' or 'falsy'. For starters just assume that callback does indeed return a boolean value)

There also is code being executed: The first statement after the condition. This is just a notational shorthand. The verbose equivalent code would be:

if (callback(array[i])) {
    newArray.push(array[i]);
}

CodePudding user response:

if (callback(array[i])) newArray.push(array[i]); simply means that callback is a function, that gets called and a return value is expected (could be any value, not only boolean). Then, if the return is truthy, the statement newArray.push(array[i]); gets executed.

(A single line if (exp) statement; can be written like this, but may sometimes hide bugs, so some linters prefer to always change it to

if (exp) {
  statement;
}

Callbacks are typically functions that get passed in as an argument (exactly as you see here) that then may get called.

CodePudding user response:

If your condition isn't working try to use a if else loop. If your statement isn't what you expect show an error message, else push array[i];

function filterArray(array, callback) {
  const newArray = [];
  for (let i = 0; i < array.length; i  = 1) {
    if (!callback(array[i])){
       console.log('Something went wrong');
  }else{
       newArray.push(array[i]);
    }
  return newArray;
}
´´´

Since you only give this piece of code, it's hard to analyze it, but this may work
  • Related