Opinions, reverse string order

Hey, new member, this community looks fantastic.
I’m an beginner/intermediate frontend dev, self-taught, I’m working on my fundamentals.
I’ve stumbled on this FCC video called " Top 10 Javascript Algorithms to Prepare for Coding Interviews" which is really great and I’m doing the exercices.
First exercise is pretty straightforward, it requires to code a function that reverses a string.
Except there are plenty of ways of doing so, I came up with 4, then stopped and realized I’m not sure which one is best. I don’t even know which criteria would determine which one is best.
Is it speed, code simplicity (which should lead to less errors), something else?

Basically I’m looking for a baseline way to assess code when multiple options offer the same result. Below are the 4 functions, I’d love to here your thoughts.
Thank you!

function reverse1 (str) {
    return Array.from(str).reduce ((previous, current)  => current + previous);
}

function reverse2 (str) {
    return Array.from(str).reverse().join('');
}

function reverse3 (str) {
    let r = ''
    for (let i = 0; i < str.length; i++) { r = str[i] + r}
    return r
}

function reverse4 (str) {
    let r = ''
    for (char of str) { r = char + r}
   return r
}

IMO, reverse2() is the best option because it uses a built-in array method, reverse(), that easily conveys to other developers (and yourself) what you are doing in just one line of code.

Makes sense! thank you so much for your reply

I would think this one is the best, it shows control of the basics, doesn’t create an unnecessary array, and it loops through only once
but at this level of computation there is no reason to consider these nitpicky resource optimization things and any is fine
I would only suggest to you conventional formatting
so

function reverse3 (str) {
    let r = ''
    for (let i = 0; i < str.length; i++) { 
        r = str[i] + r
    }
    return r
}

Thanks for your reply and suggestion, it’s true it doesn’t create an additional array.
I’m know that at this level of computation it doesn’t really matter, though that was super useful feedback, it helps me understand fundamental principles that might become useful in other contexts. Thanks a lot

You might be interested in this video:

Optimising Code - Computerphile
https://www.youtube.com/watch?v=K62EMzueWwA

But I thought the answers you got here were still interesting

1 Like

Oh thank you for the suggestion, this looks exactly what I’m looking for

1 Like