JavaScript Practice: Arrays, Loobs, Objects, Iterators - SubLength Code Challenge

I’m working on the intermediate JavaScript code challenges. Typically, if I’m having difficulty with a code and look up the solutions, I can figure out what it’s doing and how I can apply it in the future.

I am having trouble understanding the last part of the function for the subLength challenge, which goes as follows:

“Write a function subLength() that takes 2 parameters, a string and a single character. The function should search the string for the two occurrences of the character and return the length between them including the 2 characters. If there are less than 2 or more than 2 occurrences of the character the function should return 0.”

The full solution given is:

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

  return len;

I don’t understand what is happening with this part:

  if (len == -1) {
    len = i;
  } else {
    len = i - len + 1

I would love to be able to understand the logic of what is going on in this piece of the code.

Thank you in advance for any help!

1 Like

len is set to -1 initially. So, when char is found in str the first time the if statement is true and it’ll be changed to i - the index for the first occurrence of it.
The next time it finds char in str the else part will run and it’ll change len to be the difference between where i is now and len to find the length. ( and the + 1 because you want it to include both characters )

str = “bbbabbbab”
char = ‘a’
first time round len would be changed from -1 to 3
second time
len would be changed to 7 - 3 + 1 = 5


Each index is given a value of 1 to compute the length. since index 0 is part of the positions which make up the length of the string, it is given a value of 1

//computes the first index position for char
//-1 could have also  been  undefined or null
if(len == -1){

//computes the length taking into consideration that javascript arrays are zero-based indexed
}else {
len = i - len +1

it all comes down to understanding the relationship between array indices and the length of the array. the length is always greater than the maximum index. and in this example your loop index also begins at 0. other languages like python and java also have zero-based arrays; Matlab on the otherhand has matrices or vectors that begin at index 1

const str="saas"; let char="s"; const subLength = (str, char) => { let charCount = 0; let len = null; for (let i=0; i<str.length; i++) { if (str[i] == char) { charCount++; if (charCount > 2) { return 0; } if (len == null) { len = i; } else { len = i - len + 1 } } } if (charCount < 2) { return 0; } return len; }; let msg="computing sublength for 's' in 'saas': " console.log(msg+subLength(str,char))//returns 4 char="a"; msg="computing sublength for 'a' in 'saas': " console.log(msg+subLength(str,char)) // returns 2

That makes sense! Thank you for the clear explanation :slight_smile:

This is really helpful-- thank you!

1 Like

Hello guys, experimented with this to help my self learn too and here is my approach.

const numbers = [2, 23, 7, 9, 8, 52, 33, 2, 5, 14]; function occ(arr,el){ let checkerArr = [] arr.forEach((x,i)=>{ if(x == el){ checkerArr.push([x,i]) } }) if(checkerArr.length < 2 || checkerArr.length > 2){ return 0; }else{ let diff = (checkerArr[1][1] - checkerArr[0][1]) + 1 return diff } } console.log(occ(numbers,2)) //OUTPUT: 8

Happy coding! <3

1 Like

if(checkerArr.length < 2 || checkerArr.length > 2)

let diff = (checkerArr[1][1] - checkerArr[0][1]) + 1

Hi. That’s the direction I was trying to take too but I just kept confusing myself. Cheers for the good example :cowboy_hat_face:

does len have to =-1 or can I set it to 0;

could you explain why it is set to -1 initially,

also can CharCount and len be staring at 0?

You don’t want to set len to be a value that i could be, or this would give you unwanted results.

      if (len == -1) {
        len = i;
      } else {
        len = i - len + 1

With → if (len == -1)
you’re checking if len has been changed yet. If it hasn’t then i is at the first index, if it has then i is at the second index. If you set len to 0 at the start you’d need to change this if statement to;
if (len == 0)
but then you wouldn’t be able to determine if len equalled 0 because that’s its original value or the first character (index 0) is a match.
By setting it to -1 (or any negative number), you know it wont clash with a possible value for i (which can only be 0 or above).

Hope that helps

defo helps! thankyou :grin:

also sorry to pick your brains again, could you explain what the return len at the bottom of the code does and why we need it?

sorry to be a nuisance just curious( a good thing i guess??) :sweat_smile:

It’s never a bother :smiley:
The len returned will be the length between the two occurrences of the character.

First len is assigned a value of -1
Then we go through the loop.
The first time we find the character we’re looking for len gets set to the index of that character.
The second time, len gets set to i - len + 1, i.e. the value of the second index - the first index then add one because we want the inclusive length.
If we find the character a third time, then it fails the requirements and we return 0. I.e: if (charCount > 2… )
Then, once the loop has ended we do another check on the charCount. If it’s not 2 then we’ve not found the character and again return 0. I.e if (charCount < 2…)
(They’ve used ‘less than’ but could have just as easily used != (not equal) and got the same result, as in this case we know any value above 2 would have already been dealt with)
So, if the checks pass, we’ve found the character twice and len contains the value we’re looking for, and we return it from the function back to where it was called.

1 Like

that helped a lot thankyou!