Reversing String will add undefined

so, i was making a reverse string block but, every time i did, it adds undefined in it. here’s the code:

    //% block="Reverse $str"
    export function Reverse(str: string) {
        let list: string[] = []
        let s;
        for (let index = 0; index <= str.length; index++) {
            list.push(str.substr(index, 1))
        }
        list.reverse()
        for (let value of list) {
            s = s + value
        }
        return s;
    }
1 Like

index should iterate when it’s strictly less than str.length; i.e., get rid of the equals sign.

1 Like

Here’s a simpler version, as you can access individual characters in strings:

function reverse(s: string): string {
    let toReturn: string = ""
    for (let i: number = s.length - 1; i >= 0; i--) {
        toReturn += s[i]
    }
    return toReturn
}
4 Likes