An elegant interview question analyzes the difference between fn of and return fn of in js

  • 2021-07-01 06:39:06
  • OfStack

In js, we often encounter the situation of calling other functions in functions. At this time, there will be fn () and return fn (). Some beginners are often confused by these two methods. Here, an elegant interview question is used to analyze the differences between the two methods.


var i = 0;
function fn(){
 i++;
 if(i < 10){
 fn();
 }else{
 return i;
 }
}

var result = fn();
console.log(result); 

This is an interview question with hidden pits, which seems very simple. Most people may answer 10 without thinking about it. In fact, it can be seen that undefined is printed. This trap problem intuitively reflects the problem mentioned above, when we modify the line that executes fn to:


var i = 0;
function fn(){
 i++;
 if(i < 10){
 return fn();
 }else{
 return i;
 }
}

var result = fn();
console.log(result); 

At this time, you will find that the printed result finally lived up to expectations is 10.

Why is there such a big difference between adding return and not adding return here?

The main reason here is very simple. All functions of JavaScript have default return values. If return is not written at the end of the function, undefined will be returned by default. This is why in the console console of chrome, one line of undefined often appears below the writing code.

Take a closer look at this example. When i increases to 9, that is, the penultimate recursive call to fn, if there is no return, return undefined will default to return instead of continuing the next recursion. When return is added, the last recursion will continue here, that is, when i=10, jump into else and return to get the correct 10.

Having said that, a more classic example can be derived, the famous 2-point search method:


var mid = Math.floor((arr.length - 1) / 2);

function search(n, mid) {
 if (n > arr[mid]) {
 mid = Math.floor((mid + arr.length) / 2);
 return search(n, mid);
 } else if (n < arr[mid]) {
 mid = Math.floor((mid - 1) / 2);
 return search(n, mid);
 } else {
 return mid;
 }
}

var index = search(n, mid);
console.log(index); 

The 2-point search method also needs many recursive calls. One mistake that many novices often make when implementing this algorithm for the first time is to forget to add return before the recursive function, which finally leads to the return result of undefined. The reason here is similar to the previous one. Without adding return, it will lead to direct return to undefined after recursion, and will not continue the next recursion.


Related articles: