I need help to understand subLength if statement order - JavaScript Practice: Arrays, Loops, Objects, Iterators

Hello Fellow Coders!

I’m going through the Javascript practice; Arrays, Loops, Objects, Iterators and I’m perplexed on how come the
if (amountChar < 2){ return 0; } needs to be in its block scope?

this is the code ::::

const subLength = (str, char) => {
  let amountChar = 0;
  let len = -1;
  for(let i = 0; i < str.length; i++) {
    if (str[i] === char){
      amountChar++;
    if (amountChar > 2){
      return 0;
      }
    if (len == -1){
      len = i;
    } else {
      len = i - len + 1;
      }
    }
  }

> *   if (amountChar < 2){
> *       return 0;

    }
  return len;
}

Why is the if (amountChar < 2){ return 0; } statement not allowed to come after…
if (amountChar > 2){ return 0; }
??

Can anyone answer this cos this has bugged me for a couple of days now? :face_exhaling:

[JavaScript Practice: Arrays, Loops, Objects, Iterators]

Check the opening and closing brace pairs. There may be missing RBRACE below your indicated lines.

Hello mtf, thaank you for your response. I still can’t find the problem with the braces in the code. This was the code i was trying to pass through which didn’t return len at all…

const subLength = (str, char) => {
  let amountChar = 0;
  let len = -1;
  for(let i = 0; i < str.length; i++) {
    if (str[i] === char){
      amountChar++;
    if (amountChar > 2){
      return 0;
      }
    if (amountChar < 2){
      return 0;
      }   
    if (len == -1){
      len = i;
    } else {
      len = i - len + 1;
      }
    }
  }
  return len;
}
subLength('Saturday', 'a'); // returns 6

The first if inside the loop is okay since it is looking for an overflow condition and it makes sense to exit the loop and function in that event.

The second if should be outside of the loop so it can fully iterate the string before checking for underflow.

1 Like