0

my son started learning javascript, and I have been trying to learn some as well, to help keep his interest up and answer his questions. I have a little C++ experience, and I was toying with the language and tried writing the below javascript, only to see that it keeps outputting "undefined" with whatever the correct answer is. I'd really appreciate anyone shedding some light on the matter for me. Thanks.

var word = prompt("Enter some text");
var reversedWord = reverseString(word);
alert(reversedWord);

function reverseString(text)
{
    var reversedText = "";
    var length = text.length;

    for(var i = length; i >= 0; i--)
    {
    reversedText += text[i];
    }
    return reversedText;
}
1

4 Answers 4

1

Javascript uses the keyword 'undefined' to mean 'null'.

The problem observed in the above code is commonly referred as the 'Array index out of bound' error.

This is happening because of an attempt being made to access an element in an array from a position that does not exist.

In an array of n elements, the positions are numbered from 0 to n-1
I.E., from 0 to (length - 1).

Therefore, while writing a for-loop on an array, it must be ensured that the reference is made to positions from 0 to (length - 1) only.

The problem in the above code can be resolved by updating the for-loop to loop between (length - 1) and 0 only.

Here is the updated code that does not show 'undefined':

function reverseString(text) {
    var reversedText = "";
    var length = text.length;
    for(var i = (length -1); i >= 0; i--) {
        reversedText += text[i];
    }
    return reversedText;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. Dumb mistake on my part. Appreciate you explaining it!
1

The property length correspond to the amount of elements in the string. For example 'you'.length === 3. But the position of the letters is zero based (0, 1 and 2).

In your example when you say i = length -> i === 3, and text[3] === undefined.

Set the variable length to: var length = text.length - 1; and it will work.

Comments

1

the array goes from 0 to length -1 so text[length] is undefined try:

for(var i = length -1; i >= 0; i--)
{
reversedText += text[i];
}

Comments

0

You start at the index equal to the length of the string.

So given:

"Foo"
 012

It has a length of three, so you start at index 3, which is undefined.

You need to start at var i = length - 1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.