Why is this code not return true?

Why is this code not return true?
0.0 0

#1

Ok so im trying to return album’s name of Judas Priest but it keeps return false aka Nothing. Any tips?


var myStuff = [
    {
        "name" : "Selena Gomez",
        "album" : "Stars Dance",
        "year" : 2013
    },
    
    {
        "name" : "Judas Priest",
        "album" : "Rocka Rolla",
        "year" : 1974
    }
];


function myFunction(name) {
 
for (var i = 0; i < myStuff.length; i++) {
    if (myStuff[i].album === name) {
        return myStuff[i];
    } else {
        return "Nothing";
    }
}
}
myFunction("Rocka Rolla");


#2

Although your return is inside a for loop and it would appear to work for each item on the array, the fact is that it is still in the same scope as the function, so if myStuff[i].album === name is run when i equals 0 and they don’t match the return will affect the whole function and leave without doing any more operations.

For loops do not have returns so you can’t return to the top of the loop or give a different return for each item you are iterating through.

In this case the easier way is to assign the value of myStuff[i] to a variable if it matches with name and return it outside of the for loop.
If you want to return ‘Nothing’ you can either declare the initial variable with the value of ‘nothing’ and it will be changed if there is a match or declared and undefined variable and do a final if statement where if that variable is undefined you return the string ‘Nothing’


#3

Can you make a code example of what you mentioned about variable assignment? I tried doing this simmilar to challenge lookup profile freeCodeCamp Challenge Guide: Profile Lookup So its strange how it doesnt work on mine.


#4
var numbers = [6,5,3,8,2]


function myFunction(num) {
 var answer = 0;
for (var i = 0; i < numbers.length; i++) {
    if (numbers[i] === num) {
        answer = num;
    } 
}
return answer;
}
myFunction(3);

Here, the function will return the value of answer, if the number passed is in the array, answer will equate to that number otherwise it will remain as 0.


#5

Ok thank you, do you know any sources where i can practice for loop’s, if’s, and n esting if’s with loops, switch etc…?


#6

Codewars is a great page to practice functions, you can search for loops too. :slight_smile: