Can you tell me what's wrong with my code. This is one of the exercise in JavaScript Practice: Arrays, Loops, Objects, Iterators Practice intermediate JavaScript concepts with these 3 code challenges

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


My code is below What is wrong with it. it correctly prints everything:


const subLength = (word,letter) => {let arr = []; for (i = 0; i < word.length ; i++) { if (word[i] === letter) {arr.push(i)}} ; if (arr.length === 2) return arr[1] - arr[0]+1 ; else {return 0}}
1 Like

Hello, and welcome to the forums!

I’ve found that the interactive articles run the code in strict mode, but only give back a seemingly generic SyntaxError even though you may be seeing the proper results when you run it yourself.

In this case, you need to use let i = 0 in your for loop instead of just i = 0

2 Likes