The Walrus
The Walrus

Reputation: 1208

understanding the return keyword

I have this:

validateForm = () => {
    for (let i = 0; i < formInputs.length; i++) {
        const inputName = formInputs[i];

        if (!this.state.form[inputName].length) {
            return false;
        }
    }
}

which im refactoring in to this:

validateForm2 = () => {
    Object.keys(this.state.form).map(input => {
        if(!this.state.form[input].length) {
            return false
        }
        return true;
    })
}

the first one works, when i fill in my form and the function returns true, if one is empty it returns false.

however i cant seem to quite understand the return keyword to get the same result. Object.keys says it returns an array but even if I say return Object.keys... or else {return true} I don't seem to get the same result. what am I misunderstanding about return?

Upvotes: 0

Views: 68

Answers (4)

Abu Khadija
Abu Khadija

Reputation: 61

I think you can avoid using .map in favor of .every() which iterates over every single element and checks whether it has a length greater than zero.

const validateForm = (form) => Object.values(form).every((field) => field.length);
let semiEmptyForm = {
firstField : "",
secondfield : "notEmpty"
};
let nonEmptyForm = {
firstField : "notEmpty",
secondfield : "notEmpty"
};
console.log(validateForm(semiEmptyForm))
console.log(validateForm(nonEmptyForm))

Upvotes: 0

Igor
Igor

Reputation: 15893

In the first example you have only one (arrow) function which returns either false or undefined.

In the second example you have outer (arrow) function that never returns anything - undefined to the calling code, and the second function that you pass as a parameter to Array.map method. return statements inside the parameter function are not returning anything from the outer function.

validateForm2 = () => {
  var emptyItems = Object.keys(this.state.form).filter(input => {
      return !this.state.form[input].length;
  });
  return emptyItems.length == 0;
}

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386604

You could use Array#every, which uses the return value for a short circuit and for returning the check of all truthy items.

validateForm2 = () =>
    Object.keys(this.state.form).every(input => this.state.form[input].length);

Array#map utilizes the return value as new item for each item of the array for a new array, which is dicarded in the given example.

Upvotes: 1

yBrodsky
yBrodsky

Reputation: 5041

You could modify your function to do what you want it to do.

validateForm2 = () => {
    return Object.keys(this.state.form).every(input => {
      return this.state.form[input].length;
    })
  }

You are checking that every property has a length (true). If one of them doesn't, your function returns false.

Upvotes: 0

Related Questions