0

Conditional / loop statements not working as expected.

function addToCollection( title, artist, year) {
  collection.push({title, artist, year}); // adds album to array
  return {title, artist, year};  // returns newly created object
} // end of addToCollection function



console.log( addToCollection('The Real Thing', 'Faith No More', 
1989));
console.log( addToCollection('Angel Dust', 'Faith No More', 1992));
console.log( addToCollection( 'Nevermind', 'Nirvana', 1991));
console.log( addToCollection( 'Vulgar Display of Power', 'Pantera', 
1991));



function findRecord ( title ) {    //function not working!!
  for (let i = 0; i < collection.length; i++) {
    if (collection[i].title === title) {
      return collection[i].title.indexOf(title);
    } else {
      return false;
    }
  }
}

My conditional statement only checks against i=0, and doesn't loop through the rest of my array. This always returns false, unless I'm checking for the first item (which is naturally 0).

The idea is to make a function that finds a value within an array (title of album) and then return its index. If it is not in the array, then return false.

I think what's happening is that my code goes straight to the else conditional if the value I'm looking for is not at array[0].

The first function adds an album to array in the form of an object.

2 Answers2

2

Put return false outside the loop. That way, you will check all records for success before returning false

function findRecord ( title ) {    //function not working!!
  for (let i = 0; i < collection.length; i++) {
    if (collection[i].title === title) {
      return collection[i].title.indexOf(title);
    }
  }
  return false;
}
ControlAltDel
  • 33,923
  • 10
  • 53
  • 80
0

When a function touches return, the function stops, thats why it won't go to i=1, every time the if condition doesn't match, it jumps to the else statement, which return false, then the function will stop.

hkisthebest
  • 101
  • 1
  • 9