I don't understand this!
function rec(arg){
console.log(arg);
if(arg == 3)
return arg;
else
rec(arg + 1);
}
var i = rec(0);
console.log(i);
//0
//1
//2
//3
//undefined
Why inside the function 'arg' has a value but when it`s time to return it('arg == 3') it gives me 'undefined'?
Here is another one
function power(base, exponent) {
console.log(exponent);
if (exponent == 0)
return 1;
else
return base * power(base, exponent - 1);
}
console.log(power(2, 3));
//3
//2
//1
//0
//8
Why does it return '8' when 'exponent' is '0' inside the function and it should return '1'!
I now understand that I don`t understand how JS works.
In your first example, you should write the line
if(arg == 3)return arg;else rec(arg + 1);
as this
if(arg == 3)return arg;else return rec(arg + 1);
In the second example, you should change the line
return base * power(base, exponent - 1);
to
return Math.pow(base, exponent);
(actually, you should just replace the whole function with a call to pow(), you don't need to re-write it)
EDIT:
In the first example, you should have broken it town into multiple lines, then you would have seen it as a simple mistake. So, like this:
if(arg == 3)
return arg;
else
return rec(arg + 1);
And for posterity and good habits, it should be like this (in other words, use brackets)
if(arg == 3) {
return arg;
}
else {
return rec(arg + 1);
}
In your second example, you used recursion when you shouldn't have. A simple call to Math.pow() was all that you needed. Unless you wanted to log the behavior, no need to re-write the function.
EDIT:
My mistake after reading your comment. I apologize.
The flow goes like this:
console.log(power(2, 3));
then to the line
if (3 == 0)
return 1;
else
return 2 * power(2, 3 - 1); //power() returns 4, we return 8
//same as: return 2 * power(2, 2);
then to the line
if (2 == 0)
return 1;
else
return 2 * power(2, 2 - 1); //power() returns 2, we return 4
//same as: return 2 * power(2, 1);
then to the line
if (1 == 0)
return 1;
else
return 2 * power(2, 1 - 1); //power() returns 1, we return 2
//same as: return 2 * power(2, 0);
then to the line
if (0 == 0)
return 1;
else
// moot
Because your not telling it to.
function rec(arg){
console.log(arg);
if(arg == 3)return arg;
else rec(arg + 1); // < --- not a return statement
}
var i = rec(0);console.log(i);
The else block is not a return statement.
And as for your second question, that is because the 0 is coming from a nested call to the function somewhere down the line:
base * power(base, exponent - 1); // power(base, exponent - 1) would return 1 here, and base is probably 8 at that moment, so 8 * 1 would return you 8
While the previous answers give factually correct information, they don't address what you're misunderstanding.
In both cases, you're expecting the return form the recursive function to be the return of the last (innermost) invocation. That's incorrect.
The return from the innermost invocation is given to the second-to-innermost invocation; and then this continues until finally the outermost invocation returns. Only the outermost invocation's return value is seen by the caller.
So in the first example, you call rec(0).
Then rec(0) calls rec(1),
which calls rec(2),
which calls rec(3).
Then rec(3) returns the value 3 to rec(2) (because that's still running).
Then rec(2) exits without a return to rec(1)
which exits without a return to rec(0)
which exits without a return to the caller.
So the caller sees the return as undefined.
In the second case, yes, the last invocation of power() is power(2,0) which returns 1... to the running invocation of power(2,1)
which returns 2 to the running invocation of power(2,2)
... and so on until the final return seen by the caller is 8.
By the way, this is not "recursion in JavaScript". This is recursion.
Related
why is it necessary to add return statement before ternary operator in recursive function to return function output?
// This dose not work
function rec(n) {
n == 1 ? n : n + rec(n - 1);
}
// This works as return statement is added before ternary operator
function rec(n) {
return n == 1 ? n : n + rec(n - 1);
}
// This works
function rec(n) {
if (n == 1) return 1;
return n + rec(n - 1);
}
// If you would like to do this in one line then correct solution would be:
let rec = n => n == 1 ? n : n + rec(n - 1);
// Now you dont need to add the return keyword before
// This works as return statement is added before ternary operator
function rec(n) {
return n == 1 ? n : n + rec(n - 1);
}
// This works
function rec(n) {
if (n == 1) return 1;
return n + rec(n - 1);
}
A recursive function is function which calls itself during the execution. The ternary operator decides if the function need to call itself. So the return statement call the same function.
In the example n == 1 ? n : n + rec(n - 1); if n=1 then the function should return the value of n if not then the function will call itself with new value that is n-1.
You need a return because of
n + rec(n - 1);
where the rec(n-1) call needs to return a value to be able to calculate n + rec(n - 1), and that goes for each call to rec() until n reaches 1 when it just returns 1.
return is never default in ternary operation.
return is default in Arrow-function but it not default in normal function deceleration.
to return a output from a normal function execution it is always necessary to add return statement, but it is optional in case of Arrow-function.
function x() { 5;}
console.log(x()); // Opuput: undefined
let y = () => 5;
console.log(y()); // Output: 5
A conditional expression (often called a ternary) is simply an expression. It yields a value, but it doesn't do anything with it. In fact, unless it has side-effects, it's totally useless unless you either:
return it from a function,
assign its result to a variable, or
nest it in another expression in which you do one of these things
You may be confused by the fact that arrow functions with single-expression bodies return the result of that expression. It's still being returned by the function, even though you don't explicitly use return. And because of this simplicity, conditional expressions are often used as the body of arrow function.
But it should be no more surpising that you have to have return here than that you have to have it in
function add (x, y) {
return x + y;
}
If you took out the return there, the addition will still happen when the function is invoked, but it won't yield any value. It's the same thing in your original.
So, a friend shared this code to me about factorials and I kind of am having a hard time understanding how it provides the correct result seeing that it didn't go through a loop. If someone could explain it to me like I'm 5 I'd really appreciate it.
function fact(n){
if(n === 1){
return 1;
}else{
return n * fact(n - 1);
};
};
console.log(fact(5));
On the properties of the factorial, n! Can be written as n * (n-1) !.
That is, the result of the function for n can be obtained as n multiplied by the result of the function for n-1, and so on to 1 !:
function factorial(n) {
return (n != 1) ? n * factorial(n - 1) : 1;
}
alert( factorial(5) ); // 120
The recursion basis is the value 1. And you could make the basis and 0. Then the code will be a little shorter:
function factorial(n) {
return n ? n * factorial(n - 1) : 1;
}
alert( factorial(5) ); // 120
In this case, the call factorial (1) is reduced to 1 * factorial (0), there will be an additional step of recursion.
The code is a recursive function call to get the factorial of a number.
function fact(n){ // function declaration
if(n === 1){ //strict type check if n is an integer 1 not a '1'
return 1; // return back 1
}else{ // if n is not 1
return n * fact(n - 1); //return the number n multiplied by the function call fact again in which the parameter is n-1 now.
};
};
console.log(fact(5)); //print the result of function call fact(5) and print it to console.
function fact(n){
if(n === 1){
return 1;
}else{
return n * fact(n - 1);
};
};
console.log(fact(5));
It is a call which runs on the mathematical formula to calculate factorial:
n * (n-1) !
when it comes to recursion you can think of it as a function calling itself; in this case
function fact(n){
//test to see if n is 1, if so just return 1
if(n === 1)
return 1;
// multiply n by the result of calling fact(n-1)
return n * fact(n - 1);
}
console.log(fact(5));
so in this case when you call fact(5)
you would get
5 * fact(5-1) = 4 * fact(4-1)= 3 * fact(3-1) = 2 * fact(2-1) = 1
resulting in 5 * 4 * 3 * 2 * 1 = 120
it's a bit tricky of a concept to figure out at first, try inserting a console.log into the function to give you a clearer picture of what's going on.
function fact(n){
console.log(n);
//test to see if n is 1, if so just return 1
if(n === 1)
return 1;
// multiply n by the result of calling fact(n-1)
return n * fact(n - 1);
}
I'm trying to understand how recursion works in javascript. But I'm having problems even getting this function to work properly.
example problem shows calculating power and "potentially" setting the results of the calculation to innerHTML of var my header:
var myHeader= document.getElementById("myHeader");
var answer = 0;
answer = power(10, 5);
function power(base, exponent) {
if(exponent == 0)
return 0;
else
return base * power(base, exponent - 1);
}
myHeader.innerHTML = answer;
Could you please edit this example code to make it work?
Example code
I just want to use chrome debuggers so I can set a breakpoint and walk through the function one by one to see the order of operations.
I'm taking this function from eloquent javascript by Marijin Haverbeke
Your power function is wrong
function power(n, p) {
if(p == 0)
{
return 1; // see Math.pow(5, 0) for example
}
return power(n, p - 1) * n;
}
and
document.getElementById('myHeader').innerHTML = power(5, 10);
You have 2 problems :
1 You used var answer = 0, you didn't assign it to get the result from power.
2 Inside your function, you returned 0 if exponent === 0, so basically, when exponent = 0, you are returning base * power(base, 0) which equals to base * 0 which in turn equals to 0, so your function will always return 0.
var myHeader= document.getElementById("myHeader");
var answer = power(10,5);
function power(base, exponent) {
if(exponent === 0)
return 1;
else
return base * power(base, exponent - 1);
}
myHeader.innerHTML = answer;
myHeader.innerHTML = power(10,5);
If you are looking for some ref parameters like in C#: function(param1, param2, ref param3), no, JavaScript has no such parameter.
If you're just looking to get the power function working, then this is a better solution:
document.getElementById("myHeader").innerHTML = Math.pow(10,5);
I can't understand this recursion even though it's a really simple example. When it goes to power(base, exponent - 1); what is that supposed to do? How are things being multiplied when power keeps getting invoked until exponent equals 0?
function power(base, exponent) {
if (exponent === 0) {
return 1;
} else {
return base * power(base, exponent - 1);
}
}
Let's start from the beginning.
Let's say you call power(base, 0). Since exponent is 0, the function returns 1.
Now, let's say you call power(base, 1). Since exponent isn't 0 this time, the function calls power(base, exponent - 1) and multiplies it by base. (That's the key here...it takes the result from the recursive call, and adds its own twist.) Since exponent - 1 = 0, and power(base, 0) is 1, the result is effectively base * 1. Read: base.
Now on to power(base, 2). That ends up being base * power(base, 1). And power(base, 1) is base * power(base, 0). End result: base * (base * 1). Read: base squared.
And so on.
In case it wasn't obvious, by the way, this function will only work with non-negative integer exponents. If exponent is negative, or is even the tiniest bit more or less than a whole number, the function will run "forever". (In reality, you'll more than likely cause a stack overflow, once recursion eats up all of your stack.)
You could fix the function for negative powers with some code like
if (exponent < 0) return 1 / power(base, -exponent);
As for non-integers...there's no good way to solve that other than throwing an exception. Raising a number to a non-integer power makes sense, so you don't want to just truncate the exponent or otherwise pretend they didn't try to do it -- you'd end up returning the wrong answer.
This is similar to Math.pow(); it raises the base argument to the exponent argument.
For example, 2 ^ 4 is 16, so power(2, 4) would return 16. The if() statement checks to see whether the exponent (power) is zero and returns 1 if it is - any number raised to the power 0 equals 1.
The last line
return base * power(base, exponent - 1);
Is a recursive function that calls power() from within itself however many times specified by the value in exponent.
I'll try to explain recursion from the bottom up, or "from the middle" shall we say; it's probably easier to understand.
The bottom most call of power() takes 2 and 1 as it's arguments, and will return 1. This return value is then used in the second up call of power(), so this time the arguments passed are 2 and 2, which outputs 4, and so on until the top-most call to power() is passed 2 and 4 which returns 16.
Using a 2^3 example:
power(2, 3);
calls:
function power(2, 3) {
if (3 === 0) {
return 1;
} else {
return 2 * power(2, 2); //called
}
}
which leads to:
function power(2, 2) {
if (2 === 0) {
return 1;
} else {
return 2 * power(2, 1); //called
}
}
which leads to:
function power(2, 1) {
if (1 === 0) {
return 1;
} else {
return 2 * power(2, 0); //called
}
}
which leads to:
function power(2, 0) {
if (1 === 0) {
return 1; //returned
} else {
return 2 * power(2, -1);
}
}
which leads to:
function power(2, 1) {
if (1 === 0) {
return 1;
} else {
return 2 * 1; //returned
}
}
which leads to:
function power(2, 2) {
if (2 === 0) {
return 1;
} else {
return 2 * 2; //returned
}
}
which leads to:
function power(2, 3) {
if (3 === 0) {
return 1;
} else {
return 2 * 4; //returned
}
}
which ultimately returns 8, which is 2^3.
Assuming the initial call is power(10, 3)...
v-----first power() call returns base * (result of next power() call)
v-----second power() call returns base * (result of next power() call)
v-----third power() call returns base * (result of last power() call)
v------result of last power() call returns 1
(10 * (10 * (10 * (1))))
^-----return 1
^-----return base * 1 (10)
^-----return base * 10 (100)
^-----return base * 100 (1000)
Or go down the left, and up the right. Each line is a subsequent call to power() starting with power(10, 3)...
return base * power(base, 2); // return base * 100 (1000)
return base * power(base, 1); // return base * 10 (100)
return base * power(base, 0); // return base * 1 (10)
return 1; // return 1 (1)
base = 10
power = 3
10 * power(10,2)
10 * 10 * power(10,1)
10 * 10 * 10
maybe ok for positive integers...
Let's try to explain this with some maths.
f(x,y) = x^y # (1) function definition
= x * x * x * ... * x # (2) multiply x with itself y times
= x * (x * x * ... * x) # (3) rewrite using parentheses for clarity
= x * (x^(y-1)) # (4) replace the second part by (1) notation
= x * f(x, y-1) # (5) replace again by using f(x,y) notation according to (1)
f(x,0) = 1 # base case: x^0 = 1
Following this you can see that f(x,y) = x * f(x, y-1).
You can also see where
if (exponent === 0) {
return 1;
}
comes from, namely the base case that something to the 0th power always equals 1: f(x,0) = 1.
That's how this recursion was derived.
I have the following example of a recursive function, and what I don't understand is the order in which things are happening:
function power(base, exponent) {
if (exponent == 0)
return 1;
else
return base * power(base, exponent - 1);
}
When does the function return the values, at the end of all the process or each time?
A simple way to visualize what happens in recursion in general is this:
a stack of calls to the function is created: this process needs a proper termination condition to end (otherwise you'll have infinite recursion, which is evil)
the single results are popped out of the stack: each result is used to calculate the next step, until the stack is empty
I.e. if base=5 and exponent=3, the call stack is (last element on top):
5*(5*(5*1))
5*(5*(5*power(5, 0)))
5*(5*power(5, 1))
5*power(5, 2)
power(5, 3)
then every called function has real parameters and is ready to return a value (first element on top):
5*(5*(5*1))
5*(5*5)
5*25
125
Note that here the functions are calulated in inverse order: first power(5, 0), then power(5, 1), and so on.. After each calulation an element of the stack is released (i.e. memory is freed).
Hope it helps :)
It is generally helpful in understanding recursive functions such as this to work things out like you would in an algebra class. Consider:
power(3, 4)
= 3 * power(3, 3)
= 3 * (3 * power(3, 2))
= 3 * (3 * (3 * power(3, 1)))
= 3 * (3 * (3 * (3 * power(3, 0))))
= 3 * (3 * (3 * (3 * 1)))
= 3 * (3 * (3 * 3))
...
= 81
The key here is that power is calling itself exactly in the way it could call any other function. So when it does that, it waits for the function to return and uses its return value.
So if you do
var x = power(10, 2);
Your call to power will get to this line:
return base * power(base, exponent - 1)
...and call power(10, 1), waiting for that to return.
The call to power(10, 1) will, of course, get to the line:
return base * power(base, exponent - 1)
...and call power(10, 0), waiting for that to return.
The call to power(10, 0) will return 1, which is then used by the call in #2 above to complete its work and return 10 * 1 = 10, which will then let your original call in #1 above return the value 10 * 10 = 100.
When seeking to understand things like this, there's nothing quite like walking through the code with a debugger. In this modern world, you have plenty to choose from, many of which may already be on your computer.
For better visualization, just substitute the function call with the function body (may be pseudo code for instance).
function power(base, exponent) {
if (exponent == 0)
return 1;
else
return base * power(base, exponent - 1);
}
power(5, 3) expands to this
function power(5, 3) {
// exponent 3 is not 0
// return 5 * power(5, 3-1)
return 5 * function power(5, 2) {
// exponent 2 is not 0
// return 5 * power(5, 2-1)
return 5 * function power(5, 1) {
//exponent 1 is not 0
// return 5 * power(5, 1-1)
return 5 * function power(5, 0){
//exponent 0 is 0
return 1;
}
}
}
}
Now the picture is clear. It all becomes like below..
// 1
function power(5, 3){
return 5 * function power(5, 2){
return 5 * function power(5, 1){
return 5 * ( function power(5, 0){
return 1;
} )
}
}
}
// 2
function power(5, 3){
return 5 * function power(5, 2){
return 5 * ( function power(5, 1){
return 5 * 1;
} )
}
}
// 3
function power(5, 3){
return 5 * ( function power(5, 2){
return 5 * 5 * 1;
} )
}
// 4
function power(5, 3){
return ( 5 * 5 * 5 * 1 );
}
// 5
5 * 5 * 5 * 1;
As with any recursive function, the return from a particular "instance" happens when the return value has been calculated. This means that the recursed versions will then have been calculated.
So if you pass in an exponent of 4, there will be at some point 4 copies of the function being executed at one time.
This line and its resolution really trips me up:
return base * power(base, exponent - 1)
I get that the exponent is decremented until it meets the base case, but when you mulitply
the base times the recursive function call, I keep thinking "how does the function mulitply the base by itself(the base arguement)?", where is it doing that exactly, because calling base * power(base, exponent - 1) doesn't look like the standard loop contruction. How can it be calling a function with two arguements, how does it know to skip the exponent arguement and multiply the base by the base?
From a mathematical perspective:
let x = base,
let n = exponent
x*x^(n-1) = x^n
because
x^1*x^n-1=x^n (exponents of like term adds together)
It is the same as:
base * base*exponent-1.