Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript

shu Chan
shu Chan
2,951 Points

(JavaScript) I am trying to do an exercise by referencing the last indexed character in an array but...

Hello I'm doing an exercise where I must build a function which returns the last position that a number appears in an array, for example:

lastIndexOf([ 0, 1, 4, 1, 2 ], 1); should return 3

If the value never occurs, the function should return -1

but I can't seem to find the problem with the code, here it is:

function lastIndexOf(numbers,value){ var foundMatch = false; var result = 0; for(var i = (numbers.length - 1); i >= -1; i--){ if(numbers[i] === value){ foundMatch = true; result = i; } } if(foundMatch){ return result; } else { return -1; } }

console.log(lastIndexOf([ 0, 1, 4, 1, 2 ], 1), "=?", 3); console.log(lastIndexOf([ 0, 1, 4, 1, 2 ], 2), "=?", 4); console.log(lastIndexOf([ 0, 1, 4, 1, 2 ], 3), "=?", -1); console.log(lastIndexOf([ 5, 5, 5 ], 5), "=?", 2); console.log(lastIndexOf([], 3), "=?", -1);

when I run

console.log(lastIndexOf([ 0, 1, 4, 1, 2 ], 1), "=?", 3);

it returns as 1

when i run

console.log(lastIndexOf([ 5, 5, 5 ], 5), "=?", 2);

it returns as 0

I am at a lost as to why my logic would do this. Can someone help me?

4 Answers

andren
andren
28,538 Points

To illustrate the issue with your logic I'll go though what happens when [5,5,5] gets passed in to the function.

First the if statement will check if the last number equals value, since that is the case it sets result to 2. Then it continues and checks if the second to last number equals value, which it also does so it sets result equal to 1. Then it tests if the first number equals value, which it also does so it sets result equal to 0.

Based on how your code is written I assume you mean for the checking to stop once a match is found, but nothing in your code actually stops the loop when a match is found. If you added a break statement to the if statement like this:

function lastIndexOf(numbers, value) {
    var foundMatch = false;
    var result = 0;
    for (var i = (numbers.length - 1); i >= -1; i--) {
        if (numbers[i] === value) {
            foundMatch = true;
            result = i;
            break;
        }
    }
    if (foundMatch) {
        return result;
    } else {
        return -1;
    }
}

Then your code would work, as it now ends the loop once a match is found.

However your code is somewhat redundant in how it is written, if you simply place the code to return the number within the if statement and place the return -1 outside the loop then your code will work without needing the foundMatch and result variable.

Like this:

function lastIndexOf(numbers, value) {
    for (var i = (numbers.length - 1); i >= -1; i--) {
        if (numbers[i] === value) {
            return i;
        }
    }
    return -1;
}
shu Chan
shu Chan
2,951 Points

Wow what an elegant solution! Thank you! How can I show the code like you do? (in what seems to be sublime)

andren
andren
28,538 Points

Treehouse has a code box that you can use to display code in your post. If you click on the "Markdown Cheatsheet" link below the text input box you will find instructions on how to have it format the code.

But basically you just need to place three backticks and the name of the language on one line line to indicate the start of the code block like this:

```JavaScript

Then the code below that line, then you need three more backticks on a separate line. Like this:

```

To mark the end of the code block.

shu Chan
shu Chan
2,951 Points
// Like this?

Awesome thank you andren. One more question, why is it that in your less redundant answer, breaks are not required? wouldn't the logic still loop through the whole array?

andren
andren
28,538 Points

A function can only return once, meaning that a return statement essentially marks the end of the function.

So not only does the loop not continue after the return statement, nothing in the function continues after it. The function is done running once JavaScript encounters a return. This is also true in most other modern programming languages.

For example if you have a function that looks like this:

function example() {
    return 0;
    console.log("This will never be printed");
    return 1;
}

Then it would return 0, and not print out anything. Since the moment the first return is hit it would stop the function, meaning that the second and third line would never be reached.

shu Chan
shu Chan
2,951 Points

Ah thank you! That is ver helpful!