skip to Main Content

Where is undefined coming from? I thought I initialised the string correctly. (tried using debugger but can’t figure out the issue)

I’ve tried using concat() method. I’ve tried +=. Everything results in "undefined"

Why?

const reverseString = function(string) {
    let newWord = "";
    for (i = string.length; i > -1; i--) {
        newWord = newWord.concat(string[i]);
    }
    return newWord
};

Edit: in case it’s unclear when running console.log(reverseString("Hello"))

expected output would be "olleH"

actual output is "undefinedolleH"

2

Answers


  1. As @VLAZ mentioned in the comment, your string.length is more than the actual length of the string that’s why it bounces out of the array.

    There are ways you can get rid of the undefined on your string. One is what VLAZ said which is just to -1 the length. The other one is using a Nullish Coalescing Operator on your concatenation. Samples below

    const reverseString1 = function(string) {
        let newWord = "";
        for (i = string.length - 1; i > -1; i--) {
            newWord = newWord.concat(string[i]);
        }
        return newWord
    };
    
    const reverseString2 = function(string) {
        let newWord = "";
        for (i = string.length; i > -1; i--) {
            newWord = newWord.concat(string[i] ?? "");
        }
        return newWord
    };
    
    console.log(reverseString1("Hello1"));
    console.log(reverseString2("Hello2"));
    Login or Signup to reply.
  2. Index should start with (n-1), not from n

    const reverseString = function(string) {
        let newWord = "";
        for (i = string.length - 1; i > -1; i--) {
            newWord = newWord.concat(string[i]);
        }
        return newWord
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search