What is the return -1 on the third to last line of the below code? How does it work and what is its use?
function findElement(arr) {
let right_sum = 0, left_sum = 0;
for (let i = 1; i < arr.length; i++) {
right_sum += arr[i];
for (let i = 0, j = 1; j < arr.length; i++, j++) {
right_sum -= arr[j];
left_sum += arr[i];
if (left_sum === right_sum) {
return arr[i + 1];
}
}
return -1; // what is this?
}
}
The return operator is used to return a value from inside a function, so the code return -1; makes the findElement function return the value -1 (negative 1) if the for loop doesn't work. This is useful for debugging. If the for loop works, then the function will return arr[i + 1].
It looks like the developer of that piece of code decided to return -1 if the for loop failed to return a value for error checking.
Its common for people to do these kinds of returns as it helps with error handling.