Joshua Blevins
Joshua Blevins

Reputation: 697

Javascript function returns true when it should return false

I have a function that checks if a param exists in an array of inputs. It should return false but does not.

{
  ...
  validation: params => {
    const valid = ["valid", "inputs"];
    valid.forEach( v=> {
      if (!params.hasOwnProperty(v)) {
        return false;
      }
    });

    return true;
  }

So even when the if statement does evaluate to be true it never return false. This function always returns true no matter what.

Upvotes: 2

Views: 1667

Answers (2)

Amadan
Amadan

Reputation: 198294

As an alternative, use the right tool for the job. If you want to check whether every member of an array has a certain property, use every:

validation: params => {
  const valid = ["valid", "inputs"];
  return valid.every(v => params.hasOwnProperty(v));
}

Upvotes: 7

Mark
Mark

Reputation: 92440

You're return is returning from the callback function of forEach not the main function. You can't return early from a forEach without something like a throw. If you want to return early use a for...of loop instead:

validation: params => {
    const valid = ["valid", "inputs"];
    for (v of valid) {
      if (!params.hasOwnProperty(v)) {
      return false;  // this returns from the main function
    }
  };

  return true;
}

Upvotes: 4

Related Questions