Analyze the differences between fn () and return fn () in JavaScript with an elegant interview question.
In js, other functions are often called in the function. In this case, fn () is called, and return fn () is called, 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 that hides the pitfalls. It seems very simple. Most people may answer 10 questions if they don't want it. In fact, undefined is printed during running. This trap clearly reflects the problem mentioned above. When we change the line that executes fn:
var i = 0;function fn(){ i++; if(i < 10){ return fn(); }else{ return i; }}var result = fn();console.log(result);
At this time, we will find that the printed results finally meet the expectations of 10.
Why is the difference between adding or not adding return so big?
The main reason here is very simple. JavaScript Functions all return values by default. If return is not written at the end of the function, undefined is returned by default, which is why in the chrome console, the reason for undefined is often displayed below when writing code.
Let's take a closer look at this example. When I increases from 9, that is, the last and second recursive call to fn, if no return is returned, this time the fn is executed, will return undefined by default, and will not continue the next recursion. When return is added, the last recursion will continue here, that is, when I = 10, jump into else and return the correct 10.
Here, we can extend a more classic example, the famousBinary Search:
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 new users often make a mistake when implementing this algorithm for the first time, that is, they forget to add return before the recursive function, finally, the returned result is undefined. The principle here is similar to the previous one. Without return, it will lead to returning undefined directly after recursion and will not continue the next recursion.
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.