JavaScript Practice: Arrays, Loops, Objects, Iterators - Code Challenge - subLength()

Hi All,

I am working through the Javascript syntax part II course and I am having an issue with one of the 3 coding challenges called subLength(). The description of the challenge is 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.”

Examples:

* *subLength('Saturday', 'a'); // returns 6* *subLength('summer', 'm'); // returns 2* *subLength('digitize', 'i'); // returns 0* *subLength('cheesecake', 'k'); // returns 0* *

I created what I thought was a solution below and tested it in VS code several times before pasting it into codecademy and testing it again. The code appears to work but when I click on check answer I get the following message: “Double check your code. It likely has a syntax error.”

My code is as follows:

const subLength = function(string, char){ index1 = string.indexOf(char); index2 = string.lastIndexOf(char); indexa = index2 - 1; index3 = string.lastIndexOf(char, indexa); if (index1 === -1||index1 !== index3){ return 0; } else { let indexGap = (index2 - index1) + 1; return indexGap; } }; console.log(subLength('digitize', 'i')); //returns 0

After checking the solution it appears they wanted a for loop in the body of the function where I used a string method but still, the code works. There is more than one way to solve an issue in programming isnt there? VS code doesnt see a syntax error there why does codecademy? Any thoughts here would be appreciated.

The link for the challenge page is below. Thanks!!! Art

https://www.codecademy.com/paths/front-end-engineer-career-path/tracks/fecp-22-javascript-syntax-part-ii/modules/wdcp-22-practice-javascript-syntax-arrays-loops-objects-iterators/articles/fecp-javascript-practice-arrays-loops-objects-iterators

1 Like

I’m not getting a syntax error from your code on cc, but incorrect output for digitize.

There are almost always more than one ways to solve thing, maybe they just want you to do it with a loop (I’m not sure that that’s exactly the case here though). A good example is normally you don’t write your own sorting algorithm, but in interviews sometimes they ask you to implement one. In which you can’t use the built-in library.

1 Like

Perhaps try initializing the variables index1, index2, indexa, index 3 with the keyword “let” and also make sure to include the closing braces “}” for each body. That’s the only thing I am seeing that might led to a syntax error, hope that helps.

1 Like