in C Plus Plus by
What is the difference between early return and late return in a function? Can you show an example?

1 Answer

0 votes
by

Early return in a function refers to the practice of exiting or “returning” from a function as soon as it is logically possible. This often results in cleaner, more readable code and can help avoid unnecessary computation. On the other hand, late return refers to waiting until the end of the function to return a value.

Consider these two JavaScript functions:

// Early Return
function findValueEarly(arr, val) {
for (let i = 0; i < arr.length; i++) { if (arr[i] === val) return i; } return -1; } // Late Return function findValueLate(arr, val) { let result = -1; for (let i = 0; i < arr.length; i++) { if (arr[i] === val) result = i; } return result; } In the early return example, we exit the loop and function as soon as we find the desired value. In contrast, the late return version continues through the entire array even after finding the value, which could lead to unnecessary computation.

...