2

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?

GrandFleet
  • 809
  • 2
  • 10
  • 25
  • 1
    No you dont, if there's no data, nothing will happen – Greggz Oct 11 '18 at 22:00
  • 2
    This code is really strange. Treating `.map()` like `.forEach()`, pushing to state dynamically with `state[item.type]` when state only has 1 defined property with an array value, and the resulting state structure is `{ documents: { documents : [] } }`, is this intentional? – mhodges Oct 11 '18 at 22:04
  • well I shorten the code, may have added some logically errors – GrandFleet Oct 11 '18 at 22:16
  • if you can tell me what the contents of some data is expected to look like i can give you a suggestion on how to refactor this to be a lot more straightforward. – Mike Oct 11 '18 at 22:21

2 Answers2

1

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().

Mike
  • 555
  • 3
  • 14
0

Well. Actually, you should check if documents has the length property on the prototype chaing. If it doesn't and you try to use map in it, it will throw one error.

When you garantee that you have length (is iterable), length could be zero no problem. It will not iterate anything because you have no elements. Therefore, will return one empty array.

Diogo Aleixo
  • 841
  • 1
  • 8
  • 20