2

For example, suppose I have 2 arrays:

let arr1=[5,2,1];
let arr2=["abcde","ab","a"];

my work is simple : to check if length of strings in arr2 are larger than corresponding element with same index in arr1, so:

let arr1=[5,2,1];
let arr2=["abcde","ab","a"];

is true,


let arr1=[5,3,1];
let arr2=["abcde","ab","a"];

is false,


let arr1=[5,2,1,1];
let arr2=["abcde","ab","a"];

is also false. I'm struggling where I should put the checking of array length:

Style 1: put it outside for loop:

function isAllLarger(arr1,arr2){
  if(arr1.length>arr2.length){
    return false;
  }
  for(let i=0;i<arr1.length;i++){
    if(arr2[i].length<arr1[i]){
      return false;
    }
  }
  return true;
}

Style 2 : put it inside for loop:

function isAllLarger(arr1,arr2){
  for(let i=0;i<arr1.length;i++){
    if(i>=arr2.length|| arr2[i].length<arr1[i]){
      return false;
    }
  }
  return true;
}

Which one should I use?

  • 1
    This is a matter of opinion. In my opinion, I'd always select the first option as the intent of the code is clearer: check length of the arrays, then check the lengths of the elements. But that is just opinion: there's no right answer to this. – David Arno Sep 21 '18 at 8:43
  • 3
    If the specification is "if the array lengths are unequal the answer is always FALSE", then checking boundaries over and over within the loop would be both wasteful and less readable. I see no upside to Style 2. – Kilian Foth Sep 21 '18 at 10:28
2

Both are perfectly possible. But there are reasons why you should prefer option 1:

  • First, option 1 clarifies the intent: you immediately grasp the special case and understand how to handle it. With the second option an uninformed reader (or your future you?) would have to deduct from the code that there is a special case. Of course, it's feasible but not as easy as with the first option.
  • Second, option 2 requires one more condition evaluation at each iteration. But let's be honest: this argument is not the main reason, just an intellectual curiosity. The additional execution time would be marginal, and an optimizing compiler could even get rid of it.
  • Finally (thanks to John Wu for drawing attention on this), option 2 would unnecessarily process elements in the loop: we could already know the final result due to the different of length.
  • In addition to requiring one more condition evaluation each iteration, the second option also adds the overhead of iterating to begin with, since the boundary check won't find anything until the end of the array is reached and all the elements have already been examined. The first option won't have to look at a single element before bailing out. – John Wu Sep 22 '18 at 2:33
  • @JohnWu Indeed ! – Christophe Sep 22 '18 at 7:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.