Find the first duplicate number for which the second occurrence has the minimal index

Find the first duplicate number for which the second occurrence has the minimal index
0

#1
const test1 = [3, 5, 7, 9, 5, 9]
function firstDuplicate(a) {
  for (let i of a) {
    let posi = Math.abs(i) - 1
    if (a[posi] < 0) return posi + 1;
    a[posi] = a[posi]* -1 ; (*)
  }
  return -1
}

// pls explain what does the codeline “a[posi] = a[posi]* -1;” do.
As i’ve known that every statement after statement return
does nothing so why “a[posi] = a[posi]* -1;” appears here.
thanks


#2

The return statement is conditional on the if statement. That is, if (a[posi] < 0) is TRUE, then the function will return. Otherwise, the for loop will continue.


#3

Expanding on @spenguin’s answer, the function could be rewritten as

function firstDuplicate(a) {
    for (let i of a) {
        let posi = Math.abs(i) - 1
        if (a[posi] < 0) {
            return posi + 1;
        } else {
            a[posi] = a[posi]* -1 ;
        }
    }
    return -1;
}

Any clearer?