Treasure Hunter Logic

Hi Everyone iam Game Dev Project called Treasure Hunter and it is working out pretty fine. I just have a Question about the logic used in Step 17. I copied the Problem right bellow now my question is Why would the if Statement equal to -1 if they are used multiple times. While i understand that you have to check it i just dont understand why it should equla -1. Thank you in advance for your help!

Currently, there is a chance that coinCollection could have duplicate indices so we need to exclude a value after it has been picked since we don’t want multiple coins in a single plot. In this case, we will use .indexOf() to exclude a value.

Create an if statement which checks to see if calling .indexOf() on coinCollection with the argument of selectedPlot is equal to -1. Wrap this if statement around the previous step’s line of code: coinCollection.push(selectedPlot).

Documentation of the indexOf method: Array.prototype.indexOf() - JavaScript | MDN


Based on the instructions you posted, the goal is to make sure that selectedPlot is only pushed to the coinCollection array if it hasn’t already been pushed to the array, If it has already been pushed at some point in the past, then we don’t want to execute the push statement lest we end up with duplicates.

Using the indexOf method with an argument of selectedPlot will check whether selectedPlot is already present in the coinCollection array. If it isn’t found in the array, then indexOf will return -1 to signal the absence of the element in the array (if it is found, then indexOf will return a non-negative index signalling where the match was found).

So, an if statement looking to confirm that indexOf’s return value is -1 will ensure that selectedPlot is indeed not present in the coinCollection array. It is then safe to push selectedPlot to the array as there is no danger of it being a duplicate.

Thanks so much so it returns -1 unless the spot is already occupied. Now i get the logic behind it

Consider an example just in case,

let myArray = [1, 5, 10, 15, 20]

const myFunc = (arr, element) => {
    if (arr.indexOf(element) == -1) {
    } else {
        console.log("Push not needed. Element already present in array.");

myFunc(myArray, 2);     // [ 1, 5, 10, 15, 20, 2 ]
myFunc(myArray, 5);     // "Push not needed. Element already present in array."
myFunc(myArray, 15);    // "Push not needed. Element already present in array."
myFunc(myArray, 18);    // [ 1, 5, 10, 15, 20, 2, 18 ]