Home > Software design >  How to fix, "TypeError: letters.pop is not a function", issue in my code
How to fix, "TypeError: letters.pop is not a function", issue in my code

Time:03-10

I am working on a problem that requires me to reverse a string without having to change the position of characters that are not string, characters like !, (, ), | and so on.

I believe I am almost done solving the problem but I keep getting the error, TypeError: letters.pop is not a function, I tried checking what the position cause might be and i got an hint that .pop cannot be used on any data type that is not an array. I am using the .pop method on an array which is actually valid array but I still keep getting the error.

I think I am missing something out and would be glad if anyone can show it.

let word = "hello-world!"

const isLetter = (word) => {
    return word.toUpperCase() !== word.toLowerCase()
}

const letters = (word) => {
    return [...word].filter((letter) => isLetter(letter))
}

const reverseWord = [...word].map((letter) => isLetter(letter) ? letters.pop() : letter).join("")

console.log(reverseWord)

CodePudding user response:

letters.pop() is indeed not a function. pop() is a function on arrays, but letters is not an array. It's a function. Did you mean to invoke it?:

letters(word).pop()

Though keep in mind that the function returns a new array every time it's invoked. So that operation doesn't really do anything useful. Perhaps instead you meant to invoke the function immediately and only once and have letters itself store the resulting array?:

const letters = ((word) => {
    return [...word].filter((letter) => isLetter(letter))
})(word);

Note: I can't speak to whether or not this will make your entire program work as expected. The logic seems strange to me and it's possible there are other problems as well. But the main point here is just that letters itself is not an array in the original code, it's a function that returns an array.

CodePudding user response:

It's because letters was an arrow function not an array. I tried to reproduce your issue and made some changes in it. I have attached one working snippet (it's returning the string in reverse order). Hope that's how you wanted it to work.

let word = "hello-world!"

const isLetter = (word) => {
    return word.toUpperCase() !== word.toLowerCase()
}

const letters = [...word].filter((letter) => isLetter(letter))



const reverseWord = [...word].map((letter) => isLetter(letter) ? letters.pop()  : letter).join("")

console.log(reverseWord)

  • Related