Why is this code not returning correctly?

Im wondering why this code doesnt return year of a movie if i type it in. Am i missing something? Because using alert instead of return will give me No such a movie, No such a movie, No such a movie and then a year and then again No such a movie, basically a loop instead of doing it right away. Im using webtoolkitonline btw. However using return statement will only give me No such a movie.

var someArray = [
    {
        title: "A nice guy",
        year: "1980",
    },
    
    {
        title: "Batman",
        year: "1985",
    },
    
    {
        title: "Spiderman",
        year: "1990",
    },
    
    {
        title: "Love for lust",
        year: "1999",
    },
];
    
var input = prompt("What are you looking for?");
     
for (var i = 0; i < someArray.length; i++) {
        myFunction();
}
    
function myFunction() {
    if (input === someArray[i].title) {
        return someArray[i].year;
    } else {
        return "No such a movie";
    }
}
1 Like

Some part of me wants to say the you variable i is out of scope with respect to what’s inside of myFunction().

1 Like

some part of you is very right – the variable i is defined in the scope of the for loop, but the function is created and run outside that. It has no knowledge of i.

Instead, put the content of the function within the for loop.

I use console.logs to track what’s going on with the variables in my code. It helps, like doing a console.log to track what the value of input is. You only want the code to run if input is not null (if the user has answered the prompt).

Here is an example of your code that will work:

var input = prompt("What are you looking for?");


var someArray = [
    {
        title: "A nice guy",
        year: "1980",
    },
    
    {
        title: "Batman",
        year: "1985",
    },
    
    {
        title: "Spiderman",
        year: "1990",
    },
    
    {
        title: "Love for lust",
        year: "1999",
    },
];


if (input !== null) {
var search = "No such movie";
 console.log(input);
    
for (var i = 0; i < someArray.length; i++) {
    if (input == someArray[i].title) {
        search = someArray[i].year;
        break;
    } else {
        search = "No such a movie";
    }
}

console.log(search);
}
  

Why did you use var search = “No such a movie” after if (input !== null) ?

I was practicing calling functions from loops, other functions and etc… So i gave it a try lol.

“search” is just a variable being used to hold the results of the for loop.

1 Like

Oh my bad, i forgot you can change already defined variables. Thanks for you help.

1 Like

Good to know you can also use input like that too. Does that way of using it have any name or? I havent seen something like that anywhere.

EDIT: Nvm, it basically accessed object with bracket notation instead.