Practice Javascript Syntax: Why Isn't My Code to Calculate the subLength() Working?

I’ve been trying to complete the exercise to calculate subLength() in the “JavaScript Practice: Arrays, Loops, Objects, Iterators” exercise in the full stack developer course found here:

https://www.codecademy.com/paths/full-stack-engineer-career-path/tracks/fscp-javascript-syntax-part-ii/modules/fecp-practice-javascript-syntax-arrays-loops-objects-iterators/articles/fecp-javascript-practice-arrays-loops-objects-iterators

Here’s my code:

// Write function below
const subLength = (string, character) => {
  str = string
  cha = character
  
  const checkOccurences = (str, cha) => {
    let count = 0
    let position = string.indexOf(cha)
    
    while (position !== -1) {
    count++
    position = string.indexOf(cha, position + 1)
    }
    return count
  };
  
  if (checkOccurences < 2 || checkOccurences > 2) {
    return 0
  } else {
    let firstOcc = string.indexOf(character)
    let lastOcc = string.lastIndexOf(character)
    let midSection = string.substr(firstOcc, lastOcc)
    return midSection.length
  }
}

But it’s not working - I’m receiving output, but the numbers seem unrelated to the values that were passed in (e.g. console.log(subLength(‘digitize’, ‘i’)) is giving an output of 5).

Can anyone help me, please?

Hey there,
I see some issues with your code, for example:

  str = string
  cha = character

This is not the correct way to declare variables, you should precede the variable names with either const, let or var :wink:

Also, I notice that you’re never ending your lines with semicolons, I see that there are many different opinions out there about it, this thread on old codeacademy forum may be insightful

About the logic of the code I won’t say anything, each of us has its own way of doing things, however you may find comfort checking your code against the suggested solution:

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
      }
    }
  }
  if (charCount < 2) {
    return 0;
  }

  return len;
};

Cheers!

Ahh! A carry-over from coding in Python :stuck_out_tongue:

Okay, I’ll take a look at that thread.

Thanks a lot! :slight_smile:

1 Like