NealVDV
NealVDV

Reputation: 2540

Returning a boolean in .map() does not have same behavior as in for() loop?

Is there a difference in using .map() and for() when returning a boolean? See code example where the for() loop returns true, but the .map() returns nothing.

function simpleLoop(theArray) {
    // Works as expected
    for (var i = theArray.length - 1; i >= 0; i--) {
        let value = anObject[theArray[i]];

        if (!value || /^\s*$/.test(value)) {
            return true;
        }
    }
}

function simpleMap(theArray) {
    // Does not work
    theArray.map((language) => {
        const value = anObject[language];

        if (!value || /^\s*$/.test(value)) {
            return true;
        }
    });
}

simpleLoop(theArray) // <-- returns true
simpleMap(theArray) // <-- returns nothing (?)

Upvotes: 0

Views: 538

Answers (3)

jeffdill2
jeffdill2

Reputation: 4114

simpleMap isn't returning anything – it's simply creating an array.

Although @Thoelle's answer is what I'd recommend as the cleanest solution, for the sake of exhausting all options, here is a way you could accomplish what you want using the map() function:

function simpleMap(theArray) {
  const localArray = theArray.map((language) => {
    const value = anObject[language];

    if (!value || /^\s*$/.test(value)) {
        return true;
    }
  });

  return localArray.indexOf(true) > -1;
}

Upvotes: 1

Tholle
Tholle

Reputation: 112927

When you return inside the for loop, you are returning from the simpleLoop function. When you return inside map, you return from the anonymous function given to map. I would use some instead of map to get the desired effect:

function simpleSome(theArray) {
    return theArray.some((language) => {
        const value = anObject[language];
        return !value || /^\s*$/.test(value);
    });
}

Upvotes: 3

Abhinav Galodha
Abhinav Galodha

Reputation: 9928

map function doesn't modify the array. It is immutable operation. Map functions transform the array and it returns a new Array. In your case, you are not returning the modified array. You need to return the test condition outside the map callback function.

function simpleMap(theArray) {
    // Does not work
    var newArray = theArray.map((language) => {
        const value = anObject[language];

        if (!value || /^\s*$/.test(value)) {
            return true;
        }
    });
    // Return array or your condition.
    return newArray ;
}

Upvotes: 0

Related Questions