return terminates function whenever and wherever it is called.
Consider this code block -
function getSum(x, y) {
return x + y;
let product = x * y;
console.log(`sum is: ${x + y}, while product is ${product}`);
}
console.log(getSum(1, 5));
// 6
// no other console statements
return will return the control to caller - no matter what state the function is in.
You can also use conditional return, or have multiple returns in different blocks.
function doSomething(x, y) {
if (y > 100) return false;
if (x < 0 || x > y) return false;
for (let i = x; i < y; i++) {
// complex logic
const superComplexVar = 0;
if (superComplexVar == 0) return false;
}
}
There was a time in history when I used to write code for a single exit point. The flow of control would be smooth and seamless from entry to exit.
Almost anyone could understand why we are exiting out of the function, at what point, and also sprinkle the exit with custom logic (e.g. set another variable whenever exiting out of function).
function doSomething(x, y) {
let processed;
if (y < 100 && (x > 0 && x < y)) {
// code
for (let i = x; i < y; i++) {
// complex logic
const superComplexVar = 0;
if (superComplexVar == 0) {
processed = false;
break;
}
}
// more code
processed = true;
} else {
// being over explicit
processed = false;
}
return processed;
}
But, I quite don’t care about the ‘single exit point’ thing anymore.
- It looks like almost all developers are happy with
returnpopping its head now and then at multiple places in the code. - Also,
returnsare not that commonly used anywhere and everywhere within a function. It was turning out to be not that efficient logic and a chore to handle logic and ensure a single return.
So, I did the only thing that any self-respecting developer will do at this point. I fell in line.