Search code examples
javascriptarraysarrow-functions

Is Checking length of array before mapping in javascript required?


So I have this code written in ES6

 let documents = somedata;
      if (documents.length >= 0) {
          documents.map( (item, index) => {
              state[item.type].push(item);
          });
          this.setState({documents: state});
      }

and I'm trying to optimize it, do I need to check the length of an array before declaring an mapping, what would be a better way to handle error checking?

Like is there any instance in which not checking for the length would be bad?

If the variable wasn't an array it would fail, but are there any cases besides that I should be worried about?


Solution

  • no, [].map(item => item) will just return [] so you are fine if the length is 0.

    if you're just checking if your variable is an array you can refer to this question: How do you check if a variable is an array in JavaScript?

    and that could also fail for any of the following reasons

    • one of your array element wasn't an object with the property of 'type'
    • your state object didn't have a key corresponding to the item.type value
    • if the state[item.type] value wasn't an array (hence no push method)

    also, if you aren't using the result of the map, don't use map, use Array.forEach().