JavaScript Practice: Arrays, Loops, Objects, Iterators Practice intermediate JavaScript concepts with these 3 code challenges

Please can someone explain me what the variable ‘len’ is present for and which ‘len’ variable is refer to with details please ,
const subLength = (str, char) => {

let charCount = 0;

let len = -1;

for (let i=0; i<str.length; i++) {

if (str[i] == char) {

  charCount++;

  if (charCount > 2) {

    return 0;

  }

  if (len == -1) {

    len = i;

    

  } else {

    len = i - len + 1

    console.log(len)

  }

}

}

if (charCount < 2) {

return 0;

}

return len;

};

Hi,

Let’s take a step back, what do you want this function to do? Is it trying to count the amount of times a character appears in a string?

using abba, a as an example

len is set at the index that the first char that you are looking is found.
In our case:

  • a is first found at index 0
  • charCount = 0 + 1 = 1
  • i = 0
  • len = -1 so the code inside the if statement is run: len = i
  • therefore len = 0
    len currently represents the first point at which ‘a’ was found

The for loop then loops two times and hits a ‘b’ each time, that means everything in the following code is skipped and len still equals 0:

if (str[i] == char) {
      charCount++;
      if (charCount > 2) {
        return 0;
      }
      if (len == -1) {
        len = i;
      } else {
        len = i - len + 1;
      }
    }
  }

The for loop then loops one more time and hits the second ‘a’, so the code above is run for the second time:

  • index of second a = 3
  • charCount = 1 + 1 = 2
  • i = 3
  • this time len !== - 1 so the code len = i is skipped and the following code is run instead:
  • len = i - len + 1
    len represents the first point at which ‘a’ was found, i represents the second point at which ‘a’ was found
  • therefore len = 3 - 0 + 1
  • len = 4
    finally, len represents the distance between the first point and the second point at which ‘a’ was found. You add 1 back so that your total number of steps is inclusive of the first step.

using abbaa, a as an example
now imagine we had a string abbaa,

if we get to the stage we left off in the above example and then loop one more time, the code above is run for a third time, charCount is set to equal 3, if (charCount > 2) returns true and the function returns 0.

In this example, what happens to len is irrelevant because we are exiting the function before that calculation can be made, and len is never returned.

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.