Frenchiejnr
Frenchiejnr

Reputation: 326

Why does my code always end with undefined?

I wrote this JavaScript code, but it always ends **undefined**mycode? What have I done wrong/ how can I prevent this in the future. I am running my code through the chrome javascript console.

Here is my code

    //Reverse a string
//-------------------------//
//Input a string

var string = prompt("Please enter string");
            //console.log(string);

//Find length of string

var stringLength = string.length;
            //console.log(stringLength);

//Creating an empty string for outputting answer

var reversedString = "";

//Start from length of the string and work backwards, inputting letter 1 at a time.
for (var i = stringLength; i >= 0; i--){
    reversedString += string[i];
                //console.log(string[i]);
}

//Outputting the reversed string;
alert(reversedString);

Thanks for any answers in advance

Upvotes: 1

Views: 220

Answers (4)

brso05
brso05

Reputation: 13232

You should not do string[i] instead do string.charAt(i); Also change stringLength to stringLength - 1. That should fix your problem. If you want this to work across different browsers use charAt notation. Javascript arrays start at 0 not 1 that is why you do length - 1 to get the last element. For example: for a 10 element array indexes are 0-9. 10 is outside the boundaries of the array.

for (var i = (stringLength - 1); i >= 0; i--){
reversedString += string.charAt(i);

This is the correct answer.

Upvotes: 0

imike
imike

Reputation: 5656

Right code

for (var i = stringLength-1; i >= 0; i--){
    reversedString += string[i];
    console.log(string[i]);
}

Upvotes: 0

Joeppie
Joeppie

Reputation: 447

adding string[i] is the last thing this code does before alerting you, so therefore the last string[i], (first element in your array, I assume) has the value of undefined.

for (var i = stringLength; i >= 0; i--){
        reversedString += string[i];
                //console.log(string[i]);
}

I do not know on the top of my head why this is, but I know that it is always a good idea to stick to conventions, and the one for for loops is:

for(var i = 0; i < [length variable];i++) {
    ...
}

Upvotes: 0

karthikr
karthikr

Reputation: 99680

Change your loop from

for (var i = stringLength; i >= 0; i--){

to

for (var i = stringLength-1; i >= 0; i--){

The problem is, the array indices in javascript are 0 based.

Lets say the string entered in the prompt is "abc", the length of the string is 3. In the loop, you access it as string[3] which is undefined. Hence the error.

Here is the fiddle demonstrating the updated code:

Upvotes: 2

Related Questions