Javascript reference error

Unable to pinpoint the error in my code! I get the following reference error: ReferenceError: funny is not defined

I wanted to solve this problem using the indexOf() built in function and the answer doesn’t use it. Below is the task. Thanks for all help

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.

// Write function below
const subLength = (string, char) => {
  const first = string.indexOf(char)
  const second = string.indexOf(char, first + 1)
  const third = string.indexOf(char, second + 1)
  if (third == true){
    return 0
  } else if (second == -1 || first == -1) {
    return 0
  } else {
    return second - first

console.log(subLength(funny, n))

type or paste code here


Are funny and n strings if so where are they defined? Make sure you’re actually passing the required data type in.

Happy coding! :slight_smile:

I found the issue. I needed to return second - first + 1.
I also changed the if (third == true) to if (third > -1). I had assumed -1 was falsey.

1 Like