Jaws88
Jaws88

Reputation: 21

Why is this javascript variable outputting, "undefined," combined with the proper output?

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;
}

Upvotes: 0

Views: 58

Answers (4)

Gopinath
Gopinath

Reputation: 4937

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;
}

Upvotes: 1

Josiah Powell
Josiah Powell

Reputation: 21

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];
}

Upvotes: 1

Johnny Zabala
Johnny Zabala

Reputation: 2465

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.

Upvotes: 1

Quentin
Quentin

Reputation: 943100

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

Upvotes: 0

Related Questions