In js, you often encounter situations where other functions are called in functions. At this time, there will be a call method like fn(), and another is a call method like return fn(). Some beginners are often confused by these two methods. Here we use an elegant interview question 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 pitfalls. It seems very simple. Most people may answer 10 without thinking. In fact, it can be seen that what is printed is undefined. This trap question intuitively reflects the problem mentioned above. When we modify the line executing 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 is 10.
Why is there such a big difference between adding or not adding a return here?
The main reason here is very simple. JavaScript functions have default return values. If the function does not write return at the end, undefined will be returned by default. This is why in the Chrome console, when writing code, a line of undefined often appears below.
Let’s take a closer look at this example. When i increases to 9, it is the second time when fn is called recursively for the penultimate time. If there is no return, after fn is executed this time, return undefined by default, and the next recursion will not continue. 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.
Speaking of this, we can extend a more classic example, the famous binary 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 binary search method also requires multiple recursive calls. Many newbies often make mistakes when implementing this algorithm for the first time. It is to forget to add return before the recursive function, which eventually leads to the return result being undefined. The reason here is similar to the previous one. If you do not add return, it will cause you to return undefined directly after recursion, and you will not continue with the next recursion.
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.