Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Concatenating string using for loop makes it begin with 'undefined'? (javascript)

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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"

>Solution :

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"));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading