Search code examples
javascriptfunctionfor-loopstring-length

Why is my JS for loop not working? (returns "undefinded"


I was doing a JS exercise and it asked me to return a number combination in reversed order (1234 => 4321) so as always I tried do to it myself without looking for a solution and I came with:

function rev(n){
    for(i=n.length;i=0;i--){
       var reversed = reversed + n[i];
    }
    return reversed;
}
console.log(rev("test"));

But when I run this on VSCode it returns undefined to me and I do not understand which part of my code is wrong. Any ideas?


Solution

  • Okay, I understand your point. You intended to implement this and you wonder why your code is not working as expected. Kudos for your brave approach. Let's fix the issues you have step-by-step:

    Initial code

    function rev(n){
        for(i=n.length;i=0;i--){
           var reversed = reversed + n[i];
        }
        return reversed;
    }
    console.log(rev("test"));
    

    Define reversed outside the loop

    function rev(n){
        var reversed = "";
        for(i=n.length;i=0;i--){
            var reversed = reversed + n[i];
        }
        return reversed;
    }
    console.log(rev("test"));
    

    Explanation: Your code recreated it inside your loop upon each step, and assuming it was not defined somehow outside the function it would crash upon the first use. You need to properly initialize it before you concatenate anything to it.

    Fix the concatenation

    function rev(n){
        var reversed = "";
        for(i=n.length;i=0;i--){
            reversed = reversed + n[i];
        }
        return reversed;
    }
    console.log(rev("test"));
    

    Explanation: Removed the var keyword inside the loop, so you reuse reversed and correctly concatenate n[i] to it.

    Properly define i

    function rev(n){
        var reversed = "";
        for(let i = n.length - 1;i=0;i--){
            reversed = reversed + n[i];
        }
        return reversed;
    }
    console.log(rev("test"));
    

    Explanation: You need to make sure that i exists as a variable. Also, we initialize it from n.length - 1, because indexing starts from 0, so the first element has the index of 0, the second element has the index of 1 and ... and the k'th element has the index of k-1, hence the last element of n is n.length - 1 and, as you have correctly figured out, the last element must be the first element.

    Fix the continue condition

    function rev(n){
        var reversed = "";
        for(let i = n.length - 1;i>=0;i--){
            reversed = reversed + n[i];
        }
        return reversed;
    }
    console.log(rev("test"));
    

    Explanation: You assumed that the second statement inside the for is the end condition, but it is the exact opposite: it is the continue condition. It translates to plain words as "repeat as long as", instead of "repeat until".

    Do it defensively

    function rev(n){
        var reversed;
        if (typeof n === "string") {
            reversed = "";
            for(let i = n.length - 1;i>=0;i--){
                reversed = reversed + n[i];
            }
        }
        return reversed;
    }
    console.log(rev("test"));
    

    Explanation: We only do the reversion if it's a string.

    Let's support array:

    function rev(n){
        var reversed;
        if (typeof n === "string") {
            reversed = "";
            for(let i = n.length - 1;i>=0;i--){
                reversed = reversed + n[i];
            }
        } else if (Array.isArray(n)) {
            reversed = [];
            for(let i = n.length - 1;i>=0;i--){
                reversed.push(n[i]);
            }
        }
        return reversed;
    }
    console.log(rev("test"));
    console.log(rev(["t","e","s","t"]));
    

    Explanation: The algorithm is similar for arrays as for strings, but we cope with technical differences nevertheless.