JavaScript subLength() code challenge. - Solution works, but not accepted

Hi all,
I am working through the JavaScript Practice: Arrays, Loops, Objects, Iterators code challenges, and up to the subLength() question. I’ve looked at priors posts only after I came up with my own solution, but thought it best to start a new one as this is kind of unique to my solution.

My understanding is that there are no constraints on how this solution is to be achieved, and therefore can use things we have learnt up to this point.

The solution I used is somewhat different, to many others that I saw, even the solution given when I finally compared it to the answer.

The problem I am getting when I run the ‘Check Answer’ is the following message ‘Double check your code. It likely has a syntax error.

The problem is I cannot spot the error. When run it returns the expected values. I have tested it with all the checks provided and more. Each time it yields the desired answers.

If someone is able to shed some light on this that would be greatly appreciated.

const reducer = (previousValue, currentValue) => currentValue - previousValue;

function subLength(string, char) {
  strArray = string.split('');
  let index =[];
  for(let i = 0; i < strArray.length; i ++) {
    if(strArray[i] === char) {
  if (index.length < 2 || index.length > 2) {
    return 0;
  } else {
    return (index.reduce((reducer), 1));
console.log(subLength('Saturday', 'a')); // returns 6
console.log(subLength('summer', 'm')); // returns 2
console.log(subLength('digitize', 'i')); // returns 0
console.log(subLength('cheesecake', 'k')); // returns 0

I also have a solution that returns the correct answer using the tests given, but also recieve ’ **Double check your code. It likely has a syntax error. **. Maybe it is a limitation of Codecademy?

function subLength (str,char) {

let charNum= 0;

let Len = 0;

let Index1 = 0;

let Index2 = 0;

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

if (str[i] === char){

  charNum++ ; 



if(charNum === 2){

index1 = str.indexOf(char);

index2 = str.indexOf(char, index1 +1);

if (index2 !== -1 ){

 return len = (index2 + 1) - index1;


} else {return len = 0}


console.log (subLength(‘Saturday’, ‘a’)); // returns 6

console.log (subLength(‘summer’, ‘m’)); // returns 2

console.log(subLength(‘digitize’, ‘i’)); // returns 0

console.log (subLength(‘cheesecake’, ‘k’)); // returns 0

It would be nice to see formatted code. The “Getting Started” section has a description of how to post code.

There are a couple instances of white space before the ; that might be tripping up the lesson checker.

Compare your solution to the one provided. Any obvious differences?

1 Like

Thank you, I will go back and see if deleting the white spaces/; make a difference. I was a bit lazy with the formatting!

1 Like